30/09/2018, 22:54

Thắc mắc về việc khởi tạo trong java

Mọi người cho hỏi nguyên lý cua việc sao chép sau là gì:

public synchronized static void main(String[] args) {

    Thread55 ob1 = new Thread55();

   //tai sao ob2 va ob3 lai cung tham chieu toi ob1.
   
    Thread ob2 = new Thread(ob1);

    Thread ob3 = new Thread(ob1);
}

class Thread55 implements Runnable {
@Override
public void run() {
    try {
        System.out.println("" + (getN() + 1));
        setN(getN() + 1);
        Thread.sleep(800);
    } catch (InterruptedException e) {
    }
}
}

Tương tụ như:

 Set set = new HashSet();
 ArrayList arr = new ArrayList(set); // chỗ này sao lại gán được set vào arr.
                                    // có phải la add tất cả các đối tượng của set vào arr
X viết 01:08 ngày 01/10/2018

Set set = new HashSet();
ArrayList arr = new ArrayList(set);

Vào link này: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Chỗ Constructor Summary có dòng sau:

ArrayList(Collection<? extends E> c)
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection’s iterator.

Set là subinterface của thằng Collection nên truyền vào được. Công dụng thì đọc lại đoạn trên.

Bài liên quan
0