Invalid indexOf in String Array

I want to sort the String array by the second char, but the char index at position "1" is always -1, and so sorting does not work. What's wrong?

String[] wordList = outString.toString().split(", "); for (int i = 0; i < wordList.length; i++) { int n =wordList[i].indexOf(wordList.toString().charAt(1)); } Arrays.sort(wordList, 1,0); for (String str : wordList) { System.out.println(str); } 
+4
source share
4 answers

This wordList.toString().charAt(1) gives a view toString() String[] , which is probably not what you want.

 String [] test = new String [] {"a","b","c"}; System.out.println(test.toString()); 

Output

 [Ljava.lang.String;@23fc4bec 

You can find sorting by the second index easier if you use custom Comparator and allow Collections.sort() sort your list of words (after first placing it in the List ).

Also note that your split contains a space, which can lead to some confusion split(", "); .

+9
source

You want to write your own Comparator for type String, for example

 Comparator<String> secondLetterComparator = new Comparator<String>() { @Override public int compare(String a, String b) { return Character.compare(a.charAt(1), b.charAt(1)); } }; String[] wordList = { "apple", "orange", "banana" }; Arrays.sort(wordList, secondLetterComparator); System.out.println(Arrays.asList(wordList)); 

displays

 [banana, apple, orange] 

If Character.compare(char, char) not available because you are not yet in Java 7, use this line in compareTo() instead - it is less expressive, but it has the same effect:

 return a.charAt(1) - b.charAt(1); 

Note that no code protects strings with null or less than 2 characters.

+3
source

In my opinion, what are you looking for:

 Arrays.sort(T[] a, Comparator<? super T> c) 

You must create your own Comparator class:

 public class MyComparator implements Comparator<String> { public int compare(String s1,String s2) { return s1.charAt(1) - s2.charAt(1); } } 

And then call the MyComaparator constructor inside Arrays.sort as follows:

 Arrays.sort(wordList,new MyComparator()); 
+1
source

You are missing an index if you are looking

  wordList.toString().charAt(1) 

should be WordList [i] .ToString (). Charat (1)

-1
source

All Articles