java - 找不到符号(arrayList 排序集合)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4519543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:43:53  来源:igfitidea点击:

java - cannot find symbol (arrayList sort collection)

javacollections

提问by Jake

Hi i run into a problem when sorting an arrayList as following (and yes i have imported util):

嗨,我在按如下方式对 arrayList 进行排序时遇到了一个问题(是的,我已经导入了 util):

    Collections.sort(personer);

I have this list:

我有这个清单:

private List<Person> personer;

public Register() {
    personer = new ArrayList<Person>();
}

But i got the error:

但我得到了错误:

mittscript.java:45: cannot find symbol symbol : method sort(java.util.List) location: class java.util.Collections Collections.sort(personer);

mittscript.java:45: 找不到符号符号: 方法 sort(java.util.List) 位置: class java.util.Collections Collections.sort(personer);

回答by Gondim

I answered you in your other post java - alphabetical order (list)

我在你的另一篇文章java - 字母顺序(列表)中回答了你

I believe if you do it, will fix your problems.

我相信如果你这样做了,就会解决你的问题。

Collection<Person> listPeople = new ArrayList<Person>();

The class Person.java will implements Comparable

public class Person implements Comparable<Person>{

public int compareTo(Person person) {
  if(this.name != null && person.name != null){
   return this.name.compareToIgnoreCase(person.name);
  }
  return 0;
 }

}

Once you have this, in the class you're adding people, when you're done adding, type:

Collections.sort(listPeople);
Collection<Person> listPeople = new ArrayList<Person>();

类 Person.java 将实现 Comparable

public class Person implements Comparable<Person>{

public int compareTo(Person person) {
  if(this.name != null && person.name != null){
   return this.name.compareToIgnoreCase(person.name);
  }
  return 0;
 }

}

一旦你有了这个,在你要添加的班级中,当你完成添加后,输入:

Collections.sort(listPeople);

回答by Nikita Rybak

There're two sortmethods in Collections. You can either make Personimplement Comparableinterface, or provide comparator as a second argument into sort.
Otherwise, there's no way for JVM to know which Personobject is 'bigger' or 'smaller' than another.

中有两种sort方法Collections。您可以创建Person实现Comparable接口,也可以将比较器作为第二个参数提供到sort.
否则,JVM 无法知道哪个Person对象比另一个“大”或“小”。

See the docs for details.

有关详细信息,请参阅文档。

So, option 1

所以,选项 1

class Person implements Comparable {
    ...
}

Collections.sort(list);

and option 2

和选项 2

Collections.sort(list, myCustomComparator);

回答by Nikita Rybak

You should implement Comparable < T > Interface

你应该实施 Comparable < T > Interface