考虑一对通过ArrayList
添加到列表中的值和计数器。我想搜索一个新值,如果它不存在则插入,或者如果存在则增加其计数器。
class foo {
private String val;
private int count;
public foo( String s, int c )
{
val = s;
count = c;
}
}
public class bar {
public void method1() {
{
...
List<foo> myList= new ArrayList<foo>();
String nValue = getFromUser(); // assume it is a working method
int pos = myList.indexOf( nValue );
foo f = new foo( nValue, 1 );
if ( pos == -1 ) {
myList.add( f );
} else {
myList.set( pos, ????? );
}
}
}
为了写出?????,我有这个想法
else {
foo f2 = new foo( f.getValue(), f.getCounter()+1 );
myList.set( pos, f2 );
}
绝对,我必须在getValue()
中定义getCounter()
和foo{}
。有没有更好更有效的方法呢?
另一个问题是关于indexOf()
。好像它找不到现有物品的位置!以下代码显示pos为-1,尽管请求字符串(hello1)存在于myList
class foo {
private String st;
private int count;
public foo( String s, int c )
{
st = s;
count = c;
}
}
public class Test {
public static void main(String[] args) {
List<foo> myList= new ArrayList<foo>();
myList.add( new foo( "hello1", 1) );
myList.add( new foo( "hello2", 1) );
int pos = myList.indexOf( "hello1" );
if (pos == -1)
System.out.println("not found"); //goes here!!!
else
System.out.println("found");
}
}
答案 0 :(得分:2)
这不正确int pos = myList.indexOf( nValue );
,而是要解决你必须搜索你的对象,例如你可以使用一个单独的方法,搜索你的对象这里是一段代码可以帮助你:
public static void main(String[] args) {
List<foo> myList = new ArrayList<foo>();
String nValue = getFromUser();
int pos = getPosition(myList, nValue);//<-------Get position in your List
foo f = new foo(nValue, 1);
if (pos == -1) {//if your object not exist create it and add it to your List
myList.add(new foo(nValue, 1));
} else {//else increment your counter
myList.get(pos).setCount(myList.get(pos).getCount() + 1);
}
}
private static int getPosition(List<foo> myList, String nValue) {
for (int i = 0; i < myList.size(); i++) {
if (myList.get(i).getVal().equals(nValue)) {
return i;
}
}
return -1;
}
你的类foo应该实现getter和setter,例如:
class foo {
private String val;
private int count;
public foo(String s, int c) {
val = s;
count = c;
}
public String getVal() {
return val;
}
public void setVal(String val) {
this.val = val;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
你可以在这里找到一个例子Ideone
答案 1 :(得分:0)
只需为每个字段创建getter和setter。这是Java中的常见做法。
然后使用:
foo f = myList.get(pos);
f.setCounter(f.getCounter()+1);