Collections.sort()在对ArrayList进行排序时出现错误。

huangapple go评论89阅读模式
英文:

Collections.sort() error occuring while sorting ArrayList

问题

I'm trying to sort by name ArrayList elements but I couldn't solve the problem.

Could someone help?

> ERROR At case 4: Collections.sort(contact);

>

> ERROR ***"Required type: List <T> Provided: List <Data> reason: no

> instance(s) of type variable(s) T exist so that Data conforms to

> Comparable<? super T>"***

below code works fine without sort


public class AddressBook {
private static List&lt;Data&gt; contact = new ArrayList&lt;Data&gt;();
public static void main(String[] args) {
AddressBook addressBook = new AddressBook();
Scanner sc = new Scanner(System.in);
int menu;
String choice;
String choice2;
System.out.println(&quot; =========================== &quot;);
System.out.println(&quot; | 0. Exit.                |&quot;);
System.out.println(&quot; | 1. Add contact.         |&quot;);
System.out.println(&quot; =========================== &quot;);
try {
menu = sc.nextInt();
while (menu != 0) {
switch (menu) {
case 1:
while (menu != 2) {
System.out.println(&quot;Enter First Name: &quot;);
String firstName = sc.next();
System.out.println(&quot;Enter Last Name: &quot;);
String lastName = sc.next();
System.out.println(&quot;Enter Phone: &quot;);
String homePhone = sc.next();
if (homePhone.length()!=11 || !homePhone.startsWith(&quot;8&quot;)) {
System.out.println(&quot;Number should start with &#39;8&#39; and has &#39;11&#39; digit&quot; );
}else {
System.out.println(&quot;Enter Email: &quot;);
String personalWebSite = sc.next();
contact.add(new Data(firstName, lastName,
homePhone, personalWebSite));
}
System.out
.println(&quot;Would you like to add someone else? 1: Yes, 2: No&quot;);
menu = sc.nextInt();
}
break;
case 2:
System.out
.println(&quot;Enter First Name of contact that you would like to edit: &quot;);
choice = sc.next();
addressBook.deleteByFirstName(choice);
System.out.println(&quot;Enter First Name: &quot;);
String firstName = sc.next().toUpperCase();
System.out.println(&quot;Enter Last Name: &quot;);
String lastName = sc.next();
System.out.println(&quot;Enter Phone: &quot;);
String homePhone = sc.next();
System.out.println(&quot;Enter Email: &quot;);
String personalWebSite = sc.next();
contact.add(new Data(firstName, lastName,
homePhone, personalWebSite));
break;
case 3:
System.out.println(&quot;------------------&quot;);
System.out.println(&quot;1. Search number: &quot;);
System.out.println(&quot;2. Search name: &quot;);
System.out.println(&quot;------------------&quot;);
int search= sc.nextInt();
if(search==1) {
System.out
.println(&quot;Enter Number of contact: &quot;);
choice2 = sc.next();
addressBook.searchByPhoneNumber(choice2);
break;
}else {
System.out
.println(&quot;Enter First Name of contact: &quot;);
choice = sc.next();
addressBook.searchByFirstName(choice);
break;
}
case 4:
Collections.sort(contact);
//ERROR occurring here 
case 5:
System.out.println(&quot;This is a list of every contact&quot;);
System.out.println(addressBook.contact);
break;
case 6:
System.out.println(&quot;------------------&quot;);
System.out.println(&quot;1. Delete by name: &quot;);
System.out.println(&quot;2. Delete all: &quot;);
System.out.println(&quot;------------------&quot;);
int del= sc.nextInt();
if(del==1){
System.out
.println(&quot;Enter First Name of contact that you would like to delete: &quot;);
choice = sc.next();
addressBook.deleteByFirstName(choice);
break;
}else{
System.out.println(&quot;Successfully Deleted&quot;);
System.out.println(&quot;&quot;);
contact.clear();
}
break;
default:
throw new IllegalStateException(&quot;Unexpected value: &quot; + menu);
}
System.out.println(&quot; =========================== &quot;);
System.out.println(&quot; | 0. Exit.                |&quot;);
System.out.println(&quot; | 1. Add contact.         |&quot;);
System.out.println(&quot; =========================== &quot;);
menu = sc.nextInt();
}
}
catch(InputMismatchException exception)
{
System.out.println(&quot;This is not an integer&quot;);
}
System.out.println(&quot;Good-Bye!&quot;);
}
private void searchByFirstName(String firstName) {
for (Iterator&lt;Data&gt; iterator = contact.iterator(); iterator.hasNext();) {
Data temp = iterator.next();
if (temp.getFirstName().equalsIgnoreCase(firstName)) {
System.out.println(temp);
return;
}
}
System.out.println(&quot;No contact with first name &quot; + firstName
+ &quot; was found.&quot;);
}
private void searchByPhoneNumber(String homePhone) {
for (Iterator&lt;Data&gt; iterator = contact.iterator(); iterator.hasNext();) {
Data temp = iterator.next();
if (temp.getHomePhone().equalsIgnoreCase(homePhone)) {
System.out.println(temp);
return;
}
}
System.out.println(&quot;No contact with number &quot; + homePhone
+ &quot; was found.&quot;);
}
private void deleteByFirstName(String firstName) {
for (Iterator&lt;Data&gt; iterator = contact.iterator(); iterator.hasNext();) {
Data temp = iterator.next();
if (temp.getFirstName().equalsIgnoreCase(firstName)) {
iterator.remove();
return;
}
}
System.out.println(&quot;No contact with first name &quot; + firstName
+ &quot; was found.&quot;);
}
private void deleteAll(String all) {
for (Iterator&lt;Data&gt; iterator = contact.iterator(); iterator.hasNext();) {
iterator.remove();
return;
}
System.out.println(&quot;Deleting...&quot;);
}
private static int[] selectionSortAlg(int[] a, int n) {
for (int i = 0; i &lt; n - 1; i++) {
int iMin = i;
for (int j = i + 1; j &lt; n; j++) {
if (a[j] &lt; a[i
<details>
<summary>英文:</summary>
I&#39;m trying to sort by name ArrayList elements but I couldn&#39;t solve problem                            .                          .                                    .                        .                   .                    . 
Could someone help?
&gt;  ERROR At ```case 4: Collections.sort(contact);```
&gt; 
&gt; ERROR ***&quot;Required type: List &lt;T&gt; Provided: List &lt;Data&gt; reason: no
&gt; instance(s) of type variable(s) T exist so that Data conforms to
&gt; Comparable&lt;? super T&gt;&quot;***
below code works fine without sort
```import java.util.*;
public class AddressBook {
private static List&lt;Data&gt; contact = new ArrayList&lt;Data&gt;();
public static void main(String[] args) {
AddressBook addressBook = new AddressBook();
Scanner sc = new Scanner(System.in);
int menu;
String choice;
String choice2;
System.out.println(&quot; =========================== &quot;);
System.out.println(&quot; | 0. Exit.                |&quot;);
System.out.println(&quot; | 1. Add contact.         |&quot;);
System.out.println(&quot; =========================== &quot;);
try
{
menu = sc.nextInt();
while (menu != 0) {
switch (menu) {
case 1:
while (menu != 2) {
System.out.println(&quot;Enter First Name: &quot;);
String firstName = sc.next();
System.out.println(&quot;Enter Last Name: &quot;);
String lastName = sc.next();
System.out.println(&quot;Enter Phone: &quot;);
String homePhone = sc.next();
if (homePhone.length()!=11 || !homePhone.startsWith(&quot;8&quot;)) {
System.out.println(&quot;Number should start with &#39;8&#39; and has &#39;11&#39; digit&quot; );
}else {
System.out.println(&quot;Enter Email: &quot;);
String personalWebSite = sc.next();
contact.add(new Data(firstName, lastName,
homePhone, personalWebSite));
}
System.out
.println(&quot;Would you like to add someone else? 1: Yes, 2: No&quot;);
menu = sc.nextInt();
}
break;
case 2:
System.out
.println(&quot;Enter First Name of contact that you would like to edit: &quot;);
choice = sc.next();
addressBook.deleteByFirstName(choice);
System.out.println(&quot;Enter First Name: &quot;);
String firstName = sc.next().toUpperCase();
System.out.println(&quot;Enter Last Name: &quot;);
String lastName = sc.next();
System.out.println(&quot;Enter Phone: &quot;);
String homePhone = sc.next();
System.out.println(&quot;Enter Email: &quot;);
String personalWebSite = sc.next();
contact.add(new Data(firstName, lastName,
homePhone, personalWebSite));
break;
case 3:
System.out.println(&quot;------------------&quot;);
System.out.println(&quot;1. Search number: &quot;);
System.out.println(&quot;2. Search name: &quot;);
System.out.println(&quot;------------------&quot;);
int search= sc.nextInt();
if(search==1) {
System.out
.println(&quot;Enter Number of contact: &quot;);
choice2 = sc.next();
addressBook.searchByPhoneNumber(choice2);
break;
}else {
System.out
.println(&quot;Enter First Name of contact: &quot;);
choice = sc.next();
addressBook.searchByFirstName(choice);
break;
}
case 4:
Collections.sort(contact);
//ERROR occurring here 
case 5:
System.out.println(&quot;This is a list of every contact&quot;);
System.out.println(addressBook.contact);
break;
case 6:
System.out.println(&quot;------------------&quot;);
System.out.println(&quot;1. Delete by name: &quot;);
System.out.println(&quot;2. Delete all: &quot;);
System.out.println(&quot;------------------&quot;);
int del= sc.nextInt();
if(del==1){
System.out
.println(&quot;Enter First Name of contact that you would like to delete: &quot;);
choice = sc.next();
addressBook.deleteByFirstName(choice);
break;
}else{
System.out.println(&quot;Successfully Deleted&quot;);
System.out.println(&quot;&quot;);
contact.clear();
}
break;
default:
throw new IllegalStateException(&quot;Unexpected value: &quot; + menu);
}
System.out.println(&quot; =========================== &quot;);
System.out.println(&quot; | 0. Exit.                |&quot;);
System.out.println(&quot; | 1. Add contact.         |&quot;);
System.out.println(&quot; =========================== &quot;);
menu = sc.nextInt();
}
}
catch(InputMismatchException exception)
{
System.out.println(&quot;This is not an integer&quot;);
}
System.out.println(&quot;Good-Bye!&quot;);
}
private void searchByFirstName(String firstName) {
for (Iterator&lt;Data&gt; iterator = contact.iterator(); iterator.hasNext();) {
Data temp = iterator.next();
if (temp.getFirstName().equalsIgnoreCase(firstName)) {
System.out.println(temp);
return;
}
}
System.out.println(&quot;No contact with first name &quot; + firstName
+ &quot; was found.&quot;);
}
private void searchByPhoneNumber(String homePhone) {
for (Iterator&lt;Data&gt; iterator = contact.iterator(); iterator.hasNext();) {
Data temp = iterator.next();
if (temp.getHomePhone().equalsIgnoreCase(homePhone)) {
System.out.println(temp);
return;
}
}
System.out.println(&quot;No contact with number &quot; + homePhone
+ &quot; was found.&quot;);
}
private void deleteByFirstName(String firstName) {
for (Iterator&lt;Data&gt; iterator = contact.iterator(); iterator.hasNext();) {
Data temp = iterator.next();
if (temp.getFirstName().equalsIgnoreCase(firstName)) {
iterator.remove();
return;
}
}
System.out.println(&quot;No contact with first name &quot; + firstName
+ &quot; was found.&quot;);
}
private void deleteAll(String all) {
for (Iterator&lt;Data&gt; iterator = contact.iterator(); iterator.hasNext();) {
iterator.remove();
return;
}
System.out.println(&quot;Deleting...&quot;);
}
private static int[] selectionSortAlg(int[] a, int n) {
for (int i = 0; i &lt; n - 1; i++) {
int iMin = i;
for (int j = i + 1; j &lt; n; j++) {
if (a[j] &lt; a[iMin]) {
iMin = j; // index of smallest element
}
}
int temp = a[i];
a[i] = a[iMin];
a[iMin] = temp;
System.out.println(&quot;Pass...&quot; + i + &quot;...&quot; + Arrays.toString(a));
}
return a;
}
public static class Data {
private String firstName = null;
private String lastName = null;
private String homePhone = null;
private String personalWebSite = null;
public Data(String firstName,String lastName, String homePhone, String personalWebSite) {
this.firstName = firstName;
this.lastName = lastName;
this.homePhone = homePhone;
this.personalWebSite = personalWebSite;
}
public String getFirstName() {
return firstName;
}
public String getHomePhone() {
return homePhone;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String toString() {
return String.format(firstName+&quot; &quot;+lastName+&quot; &quot;+homePhone+&quot; &quot;+personalWebSite);
}
}
}
class T {
private String firstName = null;
private String lastName = null;
private String homePhone = null;
private String personalWebSite = null;
public T(String firstName,String lastName, String homePhone, String personalWebSite) {
this.firstName = firstName;
this.lastName = lastName;
this.homePhone = homePhone;
this.personalWebSite = personalWebSite;
}
public String getFirstName() {
return firstName;
}
public String getHomePhone() {
return homePhone;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String toString() {
return String.format(firstName+&quot; &quot;+lastName+&quot; &quot;+homePhone+&quot; &quot;+personalWebSite);
}
}
</details>
# 答案1
**得分**: 3
我不太确定,但我认为你需要这样做(在你的情况下是4):
```java
Collections.sort(contact, new Comparator<Data>() {
@Override
public int compare(Data contact1, Data contact2) {
return contact1.getFirstName().compareTo(contact2.getFirstName());
}
});

试一试吧,我在其他地方使用过,效果不错。希望能有所帮助。祝好运 Collections.sort()在对ArrayList进行排序时出现错误。

英文:

I am not quite sure, but I think you need to do this(in your case 4):

Collections.sort(contact, new Comparator&lt;Data&gt;() {
@Override
public int compare(Data contact1, Data contact2) {
return contact1.getFirstName().compareTo(contact2.getFirstName());
}
});

Give it a try, I had used it somewhere else, and it worked. Hope it helps. Cheers Collections.sort()在对ArrayList进行排序时出现错误。

答案2

得分: 2

你有2个选择,可以实现Comparable接口,或者为排序函数提供比较器,即:

Collections.sort(contact, (d1,d2) -> d1.firstName.compareTo(d2.firstName));

或者

contact.sort((d1,d2) -> d1.firstName.compareTo(d2.firstName));
英文:

You have 2 options whether implement Comparable or provide comparator to sorting function, i.e.

Collections.sort(contact, (d1,d2) -&gt; d1.firstName.compareTo(d2.firstName));

or

contact.sort((d1,d2) -&gt; d1.firstName.compareTo(d2.firstName));

答案3

得分: 2

按照以下方式使用:
contact.sort( Comparator.comparing(Data::getFirstName) );

英文:

Use in this way
contact.sort( Comparator.comparing(Data::getFirstName) );

答案4

得分: 0

你实现了可比较的 class Data,请看这里:

https://www.geeksforgeeks.org/comparable-vs-comparator-in-java/

public static class Data implements Comparable<Data>
    ...
    public int compareTo(Data m) {
        ...
    }
英文:

Your class Data you implement comparable, look at here:

https://www.geeksforgeeks.org/comparable-vs-comparator-in-java/

public static class Data implements Comparable&lt;Data&gt;
    ...
    public int compareTo(Data m) {
        ...
    }

答案5

得分: -1

要么在sort方法中传递一个比较器,要么让Data类实现Comparable接口并实现compareTo()方法。

@GiorgosDev提供了一个示例,其中期望数据类实现comparable接口。

英文:

Either pass a comparator in sort method or make Data class implement Comparable interface and implement compareTo()

@GiorgosDev gave an example in which data class is expected to implement comparable interface.

答案6

得分: -1

要么在Data类中实现Comparable接口,要么在sort方法中传入比较器(comparator)。例如:Collections.sort(contact, Comparator.comparing(Data::getFirstName));

英文:

Either implement comparable in Data class or pass comparator in sort method. Example Collections.sort(contact, Comparator.comparing(Data::getFirstName));

huangapple
  • 本文由 发表于 2020年6月29日 15:31:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/62633230.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定