您可以创建一个可重用的 String[] 比较器,您可以指定在哪些索引上比较数组:
public class StringArrayComparator implements Comparator<String[]> {
//we store the index to compare the arrays by in this instance variable
private final int stringIndexToCompare;
//constructor accepting the value for the index to check
public StringArrayComparator(int whichString) {
stringIndexToCompare=whichString;
}
@Override
public int compare(String[] o1, String[] o2) {
//checking if any of the arrays is null
if(o1==null) { return o2==null?0:1; } //if o1 is null, o2 determines the resuult
else if(o2==null) { return -1; } //this only gets evaluated if o1 is not null
//get the strings, by checking if the arrays are long enough
String first = o1.length>stringIndexToCompare?o1[stringIndexToCompare]:null;
String second= o2.length>stringIndexToCompare?o2[stringIndexToCompare]:null;
//null checking the strings themselves -- basically same as above
if(first==null) { return second==null?0:1; }
else if(second==null) { return -1; }
//if both non-null, compare them.
return first.compareTo(second);
}
}
要在您的列表中使用:
Collections.sort(myList,new StringArrayComparator(3));
注意:3 指定要比较的数组的索引。
您没有指定打印字符串的外观的预期输出,而只是为了打印列表,您可以使用这个 oneliner:
System.out.println(Arrays.deepToString(a.toArray()));
编辑
我想看到类似 Log.d("line number",column[0]+","+column 1 +","+column[2]+...);
嘿,看起来几乎没问题......基本上你只需要将它放入一个循环中:这会逐行打印:
int lineNo=0;
for(String[] line :myList) {
StringBuilder sb = new StringBuilder();
sb.append(++i); //line number, incrementing too
//iterating through the elements of the array
for(int col=0;col<line.lenght;col++) {
sb.append(",");
if(line[col]!=null) { //check for null....
sb.append(line[col]);
}
}
Log.d(sb.toString()); //append the value from the builder to the log.
}
要将它放在一个大字符串中:
int lineNo=0;
StringBuilder sb = new StringBuilder(); //create it here
for(String[] line :myList) {
sb.append(++i); //line number, incrementing too
//iterating through the elements of the array
for(int col=0;col<line.lenght;col++) {
sb.append(",");
if(line[col]!=null) { //check for null....
sb.append(line[col]);
}
}
sb.append("\n"); //append line break
}
Log.d(sb.toString()); //append the value from the builder to the log.
或者,为此目的使用 String.format() 可能会更好(虽然更慢),因为它提供了更好的格式:
//assembly format string
//if no line number was needed: String format = "";
String format = "%d"; //line number, %d means integer
for(int i=0;i<7;i++) {
format+=",%20s"; //%20s means left aligned, 20 wide string
}
format += "\n"; //line break;
int lineNumber=0;
for(String[] line:myArray) {
//if you didn't need the line number, it would be so easy here
//String.format(format,line); //one line, but this doesn't have the line number yet...
//with line numbers:
int iamLazyNow = 0;
String formatted = String.format(format,++lineNumber,
line[iamLazyNow++], line[iamLazyNow++],
line[iamLazyNow++], line[iamLazyNow++],
line[iamLazyNow++], line[iamLazyNow++],
line[iamLazyNow++]); //practically one line, but ugly
//you can append formatted to a StringBuilder, or print it here...
}