Java求冪集與List的淺拷貝深拷貝問題

來源:互聯網
上載者:User

標籤:引用   str   []   for   get   ret   imp   bsp   argv   

求冪集

使用回溯法,主要看集合裡每一個元素在與不在鏈表中,在與不在都會建立一個新的解;

import java.util.ArrayList;import java.util.List;public class p78 {    public List<List<Integer>> subsets(int[] nums) {        List<List<Integer>> result=new ArrayList<List<Integer>>();        backtrack(nums,0,new ArrayList<Integer>(),result);        return result;    }    //回溯    private void backtrack(int []nums,int start,List<Integer> list,List<List<Integer>> result){        //每次進來都將元素鏈表加入result        result.add(new ArrayList<>(list));        for(int i=start;i<nums.length;i++){     //無序性,每個元素往後遍曆            list.add(nums[i]);          //將當前元素加入鏈表            backtrack(nums,i+1,list,result);            list.remove(list.size()-1);     //將最後的元素刪除        }    }}
 List的淺拷貝深拷貝問題

List.add(E e)方法會傳入一個對象,實際上存的是該對象的引用,因此即使在add方法執行之後再去改變e的值也會導致存放的e的值改變,所以想要存放不同值的e對象就要在每次add()時傳入一個e的深拷貝(通常使用new E(e))實現

public class testListAdd {    public static void main(String argv[]){        testListAdd temp=new testListAdd();        temp.test();    }    public void  test(){        /**         * 測試string,因為string是不可變的,因此testString="456";時其實是新的對象,所以list一開始存放的"123"未被改變         */        String        List<String> stringList=new ArrayList<>();        String testString="123";        stringList.add(testString);        testString="456";        System.out.println(stringList.get(0));        /**         * 測試object,因為list存放的是a對象,所以在使用add後再對a操作也會將a的值改變         */        List<student> studentList=new ArrayList<>();        student a=new student(18);        studentList.add(a);        a.setAge(20);        System.out.println(studentList.get(0).getAge());        /**         * 與object相似,要想add一個不改變的list,只能add一個它的深拷貝new ArrayList(a)         */        List<List<Integer>> listList=new ArrayList<>();        List<Integer> list1=new ArrayList<>();        list1.add(1);        listList.add(list1);        listList.add(new ArrayList<>(list1));        list1.add(2);        for(List l:listList){            for(Object integer:l){                System.out.print(integer+"--");            }            System.out.println();        }    }    class student{        private int age;        student(){}        student(int age){this.age=age;}        public void setAge(int age){            this.age=age;        }        public int getAge(){            return age;        }    }}

 

Java求冪集與List的淺拷貝深拷貝問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.