2013-07-24 15 views
6

Tôi hy vọng đoạn mã sau sẽ cho tôi một tập hợp con và một bộ bổ sung.Cách Set.contains() quyết định xem đó là tập hợp con hay không?

Nhưng trên thực tế, kết quả cho thấy "Lỗi: Đây không phải là tập hợp con!"

Điều gì it.next() nhận và cách sửa đổi mã của tôi để nhận được kết quả tôi muốn? Cảm ơn!

package Chapter8; 

import java.util.HashSet; 
import java.util.Iterator; 
import java.util.Set; 

public class Three { 
    int n; 
    Set<Integer> set = new HashSet<Integer>(); 

    public static void main(String args[]) { 
     Three three = new Three(10); 
     three.display(three.set); 
     Set<Integer> test = new HashSet<Integer>(); 
     Iterator<Integer> it = three.set.iterator(); 
     while(it.hasNext()) { 
      test.add(it.next()); 
      three.display(test); 
      three.display(three.complementarySet(test)); 
     } 

    } 

    boolean contains(Set<Integer> s) { 
     if (this.set.contains(s)) 
      return true; 
     else 
      return false; 
    } 

    Set<Integer> complementarySet(Set<Integer> s) { 
     if(this.set.contains(s)){ 
      Set<Integer> result = this.set; 
      result.removeAll(s); 
      return result; 
     } 
     else { 
      System.out.println("Error: This is not a subset!"); 
      return null; 
     } 
    } 

    Three() { 
     this.n = 3; 
     this.randomSet(); 
    } 

    Three(int n) { 
     this.n = n; 
     this.randomSet(); 
    } 

    void randomSet() { 
     while(set.size() < n) { 
      set.add((int)(Math.random()*10)); 
     } 
    } 

    void display(Set<Integer> s) { 
     System.out.println("The set is " + s.toString()); 
    } 
} 
+0

Bạn cần biết Đặt api trước khi sử dụng Đặt. Vui lòng đọc hướng dẫn của tôi [Internal life of HashSet] (http://volodial.blogspot.com/2013/07/internal-life-of-hashset-in-java.html) –

+0

@VolodymyrLevytskyi Liên kết của bạn bị hỏng, là bài viết vẫn có sẵn ở nơi khác? – Noumenon

Trả lời

2

Vấn đề của bạn là trong phần này:

set.contains(s) 

điều đó không làm những gì bạn nghĩ nó, nó không mất một cuộc tranh cãi Set khác để xem nếu các thành viên của nó được chứa trong set đầu tiên. Nó thay vì trông nếu đối số thông qua nó là trong Set.

Bạn cần lặp lại tập hợp "đã chứa" và sử dụng set.contains(element) cho từng phần tử trong tập hợp chứa.

20

Bạn có thể muốn sử dụng set.containsAll(Collection <?> C) để kiểm tra xem Bộ sưu tập (Set, trong trường hợp này) là tập con của 'set'. Từ tài liệu: http://docs.oracle.com/javase/7/docs/api/java/util/Set.html#containsAll(java.util.Collection)

boolean containsAll(Collection c)

Returns true if this set contains all of the elements of the specified collection. If the specified collection is also a set, this method returns true if it is a subset of this set.

Các vấn đề liên quan