[英]ArrayList in alphabetical order (java)
I am trying to write a method that puts each string in a string array list in alphabetical order as the strings are entered. 我正在尝试编写一种方法,当输入字符串时,将每个字符串按字母顺序放在字符串数组列表中。 For example, if I enter 4 as the size of the desired array list and enter Anne, Bill, Aran, Carol, the method should print Anne, Aran, Bill, Carol. 例如,如果我输入4作为所需数组列表的大小,然后输入Anne,Bill,Aran,Carol,则该方法应打印Anne,Aran,Bill,Carol。 However, right now it only prompts me for 3 strings and does not print out anything. 但是,现在它仅提示我输入3个字符串,并且不打印任何内容。 Instead it gives this error "Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2." 而是给出了此错误“线程“主”中的异常java.lang.IndexOutOfBoundsException:索引:2,大小:2。” Why is it giving me this error? 为什么给我这个错误?
public static ArrayList<String> getOrderedListOfNames()
{
System.out.println ("How big an array?");
int size = sc.nextInt ();
ArrayList<String> names= new ArrayList<String>(size);
System.out.println ("Type in a string");
String firstInput= sc.next();
names.add(firstInput);
System.out.println ("Type in a string");
String secInput= sc.next();
if (secInput.compareTo(firstInput)>0)
names.add(secInput);
else
names.add(0,secInput);
if (size>2)
{
for (int i = 2 ; i < size ; i++)
{
System.out.println ("Type in a string");
String input= sc.next();
int entered=0;
for (int j=0; j<names.size(); j++)
{
String name1=names.get(j);
String name2=names.get(j+1);
if (input.compareTo(name1)>0 && input.compareTo(name2)<0)
{
names.add(j+1, input );
entered=1;
j=names.size();
}
}
if (entered==0)
names.add(input);
}
}
return names;
}
for list of size 2 ( for example ["a", "b"]
) you are traversing from 0 to 1 in j
but you do j + 1
that means for 1 you will try to access 2
which is definitely out of bound 对于大小为2的列表(例如["a", "b"]
),您正在j
从0遍历到1,但是您执行j + 1
,这意味着对于1,您将尝试访问2
,这肯定超出范围
either go upto < size - 1
or just use Collections.sort(yourArrayList)
要么达到< size - 1
要么仅使用Collections.sort(yourArrayList)
first build your array 首先建立你的数组
second iterate using a comparator: 使用比较器进行第二次迭代:
class LexicographicComparator implements Comparator<String> {
@Override
public int compare(String a, String b) {
return a.compareToIgnoreCase(b);
}
}
//... your code
Collections.sort(list, new LexicographicComparator());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.