C++ vector 與Java ArrayList分析

C++代碼

#include <iostream>
#include <vector>
#include <string>

using namespace std;

class Stu{
private:
	 int age;
	string name;
public:
	void setAge(int age)
	{
		this->age = age;
	}
	void setName(string name)
	{
		this->name = name;
	}
	
	int getAge()
	{
	    return this->age;
	}
	
	string getName()
	{
	    return this->name;
	}
};

int main()
{
   vector<Stu> stuList;
	Stu stu = Stu();
	stu.setName("aa");
	for(int i = 0 ; i < 3; i++)
	{
		stu.setAge(i+1);
		stuList.push_back(stu);
	}
	
	for(int i = 0 ; i < stuList.size(); i++)
	{
		cout << stuList[i].getName() << ", " << stuList[i].getAge() << endl;
	}
   return 0;
}

 

輸出結果:

aa, 1
aa, 2
aa, 3

Java代碼

public class Stu{
    private int age;
    private String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<Stu> stuList = new ArrayList<>();
        Stu stu = new Stu();
        stu.setName("aaa");

        for(int i = 0; i < 3; i++)
        {
            stu.setAge(i+10);
            stuList.add(stu);
        }
        for(Stu s : stuList)
        System.out.println(s.getName() + ", " + s.getAge());
    }

}


輸出結果:

aaa, 3
aaa, 3
aaa, 3

 

java ArrayList add源碼分析:

public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

在Java的ArrayList.add(e)中,傳入的是引用,因此當你傳入e以後,再改變e的成員,則ArrayList裏的e也同樣會改變,因爲本身e和ArrayList中的e就是同一個東西。

而C++的vector.push_back(e)則會調用拷貝構造函數,因此當你傳入e以後,再改變e的成員,則vector裏的e不會變,因爲已經是兩個對象了。

發佈了16 篇原創文章 · 獲贊 12 · 訪問量 6939
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章