0
我寫了一個非常簡單的類Sack
,它保存了一些數據,沒有特定的順序,實際的數據由ArrayList保存。我實現了類和它的方法,一切看起來都很好,但我在測試類中收到了編譯時錯誤。Java通用類由Generic ArrayList支持
袋類:
public class Sack<E>
{
//I suspect this might be the culprit, not sure if I can do this
//but it compiles fine, should this maybe be of type Object?
ArrayList<E> contents = new ArrayList<E>();
public void add(E item)
{
contents.add(item);
}
public boolean contains(E item)
{
return contents.contains(item);
}
public boolean remove(E item)
{
return contents.remove(item);
}
public Object removeRandom()
{
if(isEmpty())
{
return null;
}
else
{
int index = (int)(Math.random() * size());
return contents.remove(index);
}
}
public int size()
{
return contents.size();
}
public boolean isEmpty()
{
return contents.isEmpty();
}
}
主要類:
public class SackDriver
{
Sack<Integer> s = new Sack<Integer>();
Integer i = new Integer(2);
s.add(new Integer(1)); //<- Error
s.add(i); //<- Error
s.add(3); //<- Error
s.add(4); //<- Error
s.add(5); //<- Error
s.add(6); //<- Error
System.out.println("Size: " + s.size() + " Contains: " + s.contains(5));
}
這是我收到的每個呼叫的錯誤添加():
SackDriver.java:11: error: <identifier> expected
s.add(x);
不知道我在這裏做錯了什麼,任何幫助,將不勝感激。
在一個叫做主靜態方法:「公共靜態無效的主要(字串[] args)」 – Luciano 2012-04-12 16:06:43
謝謝你..不知道我怎麼忽略了。 – 2012-04-12 16:07:43