对象的ArrayList帮助java

时间:2013-03-29 03:50:09

标签: arraylist

好的,所以我的计算机类的任务很简单(它应该显示遍历数组和东西)。我不得不创建一个带有数组的版本和一个带有arrayLists的版本,所以在tester类中我有一些静态方法,但是当我使用arrayList时,我尝试从该类的对象调用一个方法(它是一个getter方法) )我得到的是一条错误消息,表示无法找到它。

以下是我的代码的缩短版本:

import java.util。*; import java.util.List;

public class testCandidate2 {

public static int getTotal(ArrayList election)
{
    int total = 0;
    for(int b = 0; b <election.size(); b++)
          total += election.getNumVotes();
    return total;
}


public static void main(String[] args)
{
    int totalVotes;
    List <Candidate> election = new ArrayList<Candidate>(5);
    election.add() = new Candidate(5000, "John Smith");

    totalVotes = getTotal(election);

}

}

公共班候选人 {

private String name;
private int numVotes;

Candidate(int nv, String n)
{
    name = n;
    numVotes = nv;
}

public String getName()
{
    return name;
}

public int getNumVotes()
{
    return numVotes;
}

public String toString()
{
    return name + " recieved " + numVotes + " votes.";
}

}

1 个答案:

答案 0 :(得分:0)

试试这个:

import java.util.*;
//import java.util.List;

public class testCandidate2 {

public static int getTotal(ArrayList election)
{
    int total = 0;
    for(int b = 0; b <election.size(); b++)
         {
         Candidate ele = (Candidate) election.get(b);
       //  System.out.println(ele.getNumVotes());
         total += ele.getNumVotes();
         //System.out.println(o.getNumVotes());
    }
         //System.out.println( (Candidate) (election.get(b).getNumVotes());
          //.getNumVotes();
    return total;
}


public static void main(String[] args)
{
    int totalVotes;
    ArrayList <Candidate> election = new ArrayList<Candidate>(5);
    election.add(new Candidate(5000, "John Smith"));

    totalVotes = getTotal(election);
    System.out.println(totalVotes);
}
}