为什么if语句不能与我的布尔arraylist一起使用?

时间:2011-11-18 11:40:56

标签: java arrays arraylist

我在这里要做的是始终从我的String arraylist中获取一个随机值,为此我正在使用另一个包含与字符串相同数量的布尔值的arraylist。

当我需要随机字符串时,我这样做:

randomstring = r.nextInt(100);
String mystring = c.getAnswear(randomstring);

if(c.getAnswear(randomstring) == null){
    randomstring = r.nextInt(100);
    mystring = c.getAnswear(randomstring);
    System.out.println("Random again!!!!!!!!!!!!!!!");
}

这就是它在c.getAnswear

中的样子
List<String> strings = new ArrayList<String>();
strings.add("blablabla");
//And another 100 of theese
//Then we have theese boolean array
ArrayList<Boolean> trueornot = new ArrayList<Boolean>();
trueornot.add(false);
//Another 100 of them
//Then we have this
String Answear = null;
if(trueornot.get(indexNum).equals(true)){
   Answear = null;
   System.out.println(Answear);
   System.out.println("Already used string random again!");
}
else if(trueornot.get(indexNum).equals(false)){
    trueornot.add(indexNum, true);
    Answear = strings.get(indexNum);
    System.out.println(Answear);
    System.out.println("Something in the array was set to true");
}
return Answear;

但是当我尝试这样做时,可以随机化我的字符串我想要多少并打印到控制台的东西被设置为true但我看到很多次相同的字符串再次被使用而且System.out.println("Already used string random again!");永远不会被打印出来控制台

当我调用此getAnswear时,我有if语句(c.getAnswear(randomstring) == null)System.out.println("random again!!!!!!!");内的行永远不会进入控制台。

我怎样才能让它发挥作用?好像getAnswear里面的答案字符串永远不会为空,这很奇怪,因为我把布尔值设置为真。

2 个答案:

答案 0 :(得分:3)

trueornot.add(indexNum, true)
这会将值添加到列表中,并将该索引处的先前值向下移动到列表中。

你应该使用trueornot.set(...)替换值......

更新

  

这就是它在c.getAnswear

中的样子
List<String> strings = new ArrayList<String>();

strings.add("blablabla");

//And another 100 of theese
//Then we have theese boolean array

ArrayList<Boolean> trueornot = new ArrayList<Boolean>();

trueornot.add(false);

//Another 100 of them
//Then we have this

如果每次调用getAnswer时实际发生这种情况,那么每次都会重新创建字符串和布尔列表,之前的所有更改都会丢失。
stringstrueornot应该是类字段而不是局部变量。

答案 1 :(得分:2)

可能是,你想将你的值设置为true,而不是插入它吗?

你这样做:

trueornot.add(indexNum, true);

但是要设置一个值,你必须这样做:

trueornot.set(indexNum, true);
相关问题