开发者

How should we use vectors in Java, as we used them in C++?

I wanted to make a class GradeBook, then create an object for each student, and save their name and courseName and Grade in a vector, then in the end, print them all. Here's my code:

public static void main(String [] args)
    {
        Vector<GradeBook> gVec = new Vector<GradeBook>() ;
        Scanner sc = new Scanner (System.in) ;

        String sName = sc.nextLine();
        String cName = sc.next();
        int grade = sc.nextInt() ;
        while(!sName.equals("end"))
        {
            GradeBook st = new GradeBook() ;
            st.setCouseInfo(sName, cName, grade) ;
            gVec.add(st) ;
            sName = sc.nextLine();
            cName = sc.next();
            grade = sc.nextInt() ;
        }
    }

The prgoram gets name, checks if it's "end" or not, then gets the courseName and the grade, sets them to GradeBook Fields which are studentName, courseName and courseGrade, then it adds them to a vector of GradeBook.

But in the end of the program I have a problem printing the results, it can't be done like how I did it in C++, like:

for ( int i=0;i<gVec.size();i+开发者_运维知识库+)
{
System.out.println(gVec[i].studentName);
System.out.println(gVec[i].courseName);
System.out.println(gVec[i].courseGrade);
}

Can someone give me a tip on how to use vectors in java? Thanks!


The method you want is Vector.get(int i). See here for more details.

I wouldn't use Vector, however. I would prefer an ArrayList, or LinkedList. Why ? You pay a (small) performance penalty for Vectors being synchronised on each operation by default, and the synchronisation pattern (per-method) not hugely useful. See this answer for more details.


You can't access to vector elements via [], you should use gVec.get(i) instead, or use foreach loop

    for (GradeBook bookItem : gVec){
System.out.println(bookItem.studentName);
System.out.println(bookItem.courseName);
System.out.println(bookItem.courseGrade);
}

Also Vector is synchronized, if your work in single thread look at ArrayList or LinkedList

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜