public class WordArray {
public char[] str;
public int[] index;
}
This is a class which stores words in the character array str
public class DuplicateArray {
WordArray wordArray[];
int size;
public static DuplicateArray getDupArray(int size , String string[]){
DuplicateArray da = new DuplicateArray();
da.size = size;
da.wordArray = new WordArray[da.size];
for (int i = 0; i < da.size; i++) {
da.wordArray[i] = new WordArray();
da.wordArray[i].str = new char[string[i].length()];
da.wordArray[i].index = new int[da.size];
da.wordArray[i].str = string[i].toCharArray();
da.wordArray[i].index[i] = i;
}
return da;
}
}
This class uses the WordArray
class and copies the individual words from the String array string
to the character str
array in each wordArray[i]
.
First I want to sort the individual characters that are stored in the str
's of each wordArray
.
Then I want to sort the each word in the wordArray
but I want to retain the original indexes of the words in string
for later use.
For that I am using this class:
public class PrintAnagram {
public static void printAnagram(String[] string) {
DuplicateArray da = DuplicateArray.getDupArray(string.length, string);
for (int i = 0; i < string.length; i++) {
Arrays.sort(da.wordArray[i].str);
}
Arrays.sort(da.wordArray);
for (int i = 0; i < string.length; i++){
System.out.println(string[da.wordArray[i].index[i]]);
}
}
}
But Class caste exceptions occurs in ComparableTimsort or something , about which , I have no idea.
From what I have read in previous question , we have to override the compareTo
.
But I don't know where to override it, Should I overide it in PrintAnagram
class , where I am actually sorting or should I override it in WordArray
or in DuplicateArray
. If anyone has the time to explain this stuff then please or you can point me to some resource where all this is clearly explained. I am fairly new to Java.
Exceptions :
Exception in thread "main" java.lang.ClassCastException: self.study.WordArray cannot be cast to java.lang.Comparable
at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:290)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:157)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:146)
at java.util.Arrays.sort(Arrays.java:472)
at self.study.PrintAnagram.printAnagram(PrintAnagram.java:13)
at self.study.AnagramTogether.main(AnagramTogether.java:7)