ArrayList 的 lastIndexof
ArrayList lastIndexof
import java.util.Scanner;
import java.util.*;
public class bracketMatch {
public bracketMatch() {
}
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("enter seq");
String[] seq = scan.nextLine().split("");
ArrayList<String> temp = new ArrayList<>();
int x = 0;
String check = null;
System.out.println(Arrays.toString(seq));
for(String brak : seq)
{
switch(brak)
{
case "(":
temp.add("(");
break;
case "[":
temp.add("[");
break;
case "{":
temp.add("{");
break;
case "<":
temp.add("<");
break;
case ")":
temp.add( ")");
break;
case "]":
temp.add("]");
break;
case "}":
temp.add("}");
break;
case ">":
temp.add(">");
break;
}
}
x = temp.lastIndexOf("(");
System.out.println( x);
/* if(x != -1)
{
temp.remove(check);
temp.remove(x);
}*/
System.out.println(temp.toString()) ;
}
}
上面的代码是匹配括号的,但是我偶然发现了ArrayList
方法lastIndexOf
。
但是,它没有获取正确的索引并且像 indexOf
方法一样工作。
我应该使用堆栈还是 linkedlist
而不是 ArrayList
?
此外,任何关于迭代 arraylist 和删除其元素的帮助,因为迭代器和 foreach 会出错。
你能给我们更多的信息吗?方法 lastIndexOf 正常工作,它为您提供列表中最后一次出现的对象,它不像 indexOf 那样工作。如果你想从 arraylist 中删除最后一次出现的“(”,只需取消注释你的 temp.remove(x) 行。
import java.util.Scanner;
import java.util.*;
public class bracketMatch {
public bracketMatch() {
}
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("enter seq");
String[] seq = scan.nextLine().split("");
ArrayList<String> temp = new ArrayList<>();
int x = 0;
String check = null;
System.out.println(Arrays.toString(seq));
for(String brak : seq)
{
switch(brak)
{
case "(":
temp.add("(");
break;
case "[":
temp.add("[");
break;
case "{":
temp.add("{");
break;
case "<":
temp.add("<");
break;
case ")":
temp.add( ")");
break;
case "]":
temp.add("]");
break;
case "}":
temp.add("}");
break;
case ">":
temp.add(">");
break;
}
}
x = temp.lastIndexOf("(");
System.out.println( x);
/* if(x != -1)
{
temp.remove(check);
temp.remove(x);
}*/
System.out.println(temp.toString()) ;
}
}
上面的代码是匹配括号的,但是我偶然发现了ArrayList
方法lastIndexOf
。
但是,它没有获取正确的索引并且像 indexOf
方法一样工作。
我应该使用堆栈还是 linkedlist
而不是 ArrayList
?
此外,任何关于迭代 arraylist 和删除其元素的帮助,因为迭代器和 foreach 会出错。
你能给我们更多的信息吗?方法 lastIndexOf 正常工作,它为您提供列表中最后一次出现的对象,它不像 indexOf 那样工作。如果你想从 arraylist 中删除最后一次出现的“(”,只需取消注释你的 temp.remove(x) 行。