[英]Connect a string and a double in a ArrayList
Is it possible to connect a string
and a double
in a ArrayList
? 是否可以在
ArrayList
连接string
和double
ArrayList
?
It should look this way: 它应该看起来像这样:
[itemA 1, itemB 10, itemC 5, ...]
I tried it with write the double
also as String
in the ArrayList
, but then 我尝试过将
double
也写为ArrayList
String
来尝试,但是
Collections.sort(list)
won't sort the doubles correct. Collections.sort(list)
不会正确排序双打。
That's when you make a class. 那是您上课的时间。
class MyObject {
private String someString;
private double someDouble;
// Getters & setters
}
List<MyObject> myList = new ArrayList<>();
You can just keep a list of this custom object. 您可以仅保留此自定义对象的列表。
If you want to be able to sort your list on the double
value, simply construct your class to implement the Comparable
interface. 如果希望对
double
值的列表进行排序,只需构造您的类即可实现Comparable
接口。
class MyObject : Comparable<MyObject>{
private String someString;
private double someDouble;
@override
public int compareTo(MyObject o) {
return this.someDouble.compareTo(o.getSomeDouble());
}
}
You can create a class like, MyClass and create a String variable and double value. 您可以创建MyClass之类的类,并创建String变量和double值。
Like, 喜欢,
class MyClass
{
private String strVlaue;
private String doubleValue;
//Constructor using fields, and getter/setter method
}
Since you want to make it in order by double Value. 由于要按双倍值顺序排列。
You can either make MyClass implement Comparable and implement custom order in compareTo method OR create a comparator for MyClass 您可以使MyClass实现Comparable并在compareTo方法中实现自定义顺序,也可以为MyClass创建一个比较器
1 Implements Comparable 1实现可比
public class MyClass implements Comparable {
private String strVlaue;
private double doubleValue;
public MyClass(String strVlaue, double doubleValue) {
this.strVlaue = strVlaue;
this.doubleValue = doubleValue;
}
@Override
public int compareTo(Object o) {
MyClass mc = (MyClass) o;
return Double.compare(this.doubleValue, mc.getDoubleValue());
}
public String getStrVlaue() {
return strVlaue;
}
public void setStrVlaue(String strVlaue) {
this.strVlaue = strVlaue;
}
public double getDoubleValue() {
return doubleValue;
}
public void setDoubleValue(double doubleValue) {
this.doubleValue = doubleValue;
}
}
Use Collections.sort(List<MyClass>)
to sort. 使用
Collections.sort(List<MyClass>)
进行排序。
2 Keep MyClass not implement Comparable, create a comparator. 2保持MyClass不实现Comparable,创建一个比较器。
public class MyComparator implements Comparator<MyClass>{
@Override
public int compare(MyClass o1, MyClass o2) {
return Double.compare(o1.getDoubleValue(), o2.getDoubleValue());
}
}
Use Collections.sort(List<MyClass>, new MyComparator())
to sort. 使用
Collections.sort(List<MyClass>, new MyComparator())
进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.