I have a 2D array which contains the strings as letters starting from A goes to row 0 and from B goes to row 1 and etc..we can use charAt method and ASCII value for A is 65 and B is 66 and so on. Its a method that takes an argumen开发者_高级运维t a String and deletes the parameter from the corresponding row and also deletes the entire row of the Structure. The only thing wrong IN THE FOLLOWING CODE is the remove method.
public AlphaList() {
this.list=new String[26][];
for (int row=0; row<this.list.length; row++) {
list[row]=new String[0];
}
}
public void insert(String value) {
int firstChar=(int) value.charAt(0)-65;
String[] newList=new String[list[firstChar].length+1];
newList[newList.length-1]=value;
for(int i=0; i<list[firstChar].length;i++){
newList[i]=list[firstChar][i];
}
list[firstChar]=newList;}
public void remove(String value) {
int firstChar=(int) value.charAt(0)-65;
String[] newList=new String[list[firstChar].length-1];
newList[newList.length-1]=value;
for(int i=0; i<list[firstChar-1].length;i++){
newList[i]=list[firstChar-1][i];
}
list[firstChar]=newList;
}
According to the code of the function you delete the last two elements and save the function argument on the last cell. You need to write a function that find the index of the stored parameter (if it exist) and the use this code to delete it from array:
public void remove(String value) {
int firstChar=(int) value.charAt(0)-65;
int index = FindIndex(list[firstChar],value); // Function that return the index of value
String[] newList=new String[list[firstChar].length-1];
for(int i=0; i<index ;i++)
newList[i]=list[firstChar-1][i];
for(int i=index; i<list[firstChar-1].length;i++)
newList[i]=list[firstChar-1][i+1];
list[firstChar]=newList;
}
精彩评论