java LinkedHashSet<String>(); 中有个‘其它’值将这个值排到最后
时间: 2024-02-24 22:56:02 浏览: 25
Java中的LinkedHashSet是一种有序的集合,它会按照元素的插入顺序进行排序。如果您想把某个特定的值排在最后,可以考虑自定义一个类来继承LinkedHashSet,并重写add方法来实现。具体来说,您可以在重写add方法时,检查新加入的元素是否为特定值,如果是,就先将其从集合中删除,然后再添加到集合的末尾。以下是一个示例代码:
```java
public class MyLinkedHashSet extends LinkedHashSet<String> {
private String specialValue;
public MyLinkedHashSet(String specialValue) {
this.specialValue = specialValue;
}
@Override
public boolean add(String s) {
if (s.equals(specialValue)) {
super.remove(s);
return super.add(s);
} else {
return super.add(s);
}
}
}
// 使用自定义LinkedHashSet创建集合对象
LinkedHashSet<String> set = new MyLinkedHashSet("其它");
```
在上面的示例中,我们创建了一个MyLinkedHashSet类,它继承自LinkedHashSet,并重写了add方法。在add方法中,我们检查新添加的元素是否为特定值,如果是,就先将其从集合中删除,然后再添加到集合的末尾。最后,我们使用自定义的MyLinkedHashSet类来创建集合对象。这样,当我们向集合中添加元素时,特定值就会被排在最后。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)