2012-06-11 295 views
0

我正在爲人員開發一個班級,我對此有一個或兩個問題。如何解決此警告?

/** 
* ADT for persons which is completed which subclasses 
* to creating actors with specific properties 
*/ 
public class Person { 

    /** 
    * Name of the Person. 
    */ 
    public String name; 

    /** 
    * The World which this Person is associated with. 
    */ 
    public World world; 

    /** 
    * Tells where this Person is at the moment. 
    */ 
    public Place where; 

    /** 
    * The inventory, contains Things. 
    */ 
    public Collection<Thing> inventory; 

    /** 
    * Shows how the Person looks like 
    */ 
    public Image appearance; 

    /** 
    * Create Person named `name' in world `world'. 
    * 
    * @param world The world where the Person is created. 
    * @param name Name of the Person. 
    * @param app An image used to display the Person. 
    */ 
    public Person(World world, String name, Image app) { 
    this.world = world; 
    this.name = name; 
    this.appearance = app; 

    where = world.defaultPlace(); 
    where.enter(this); 

    inventory = Collections.synchronizedCollection(new LinkedList()); 
    } 

...

  1. 如果Person類是公共的,或者可以默認訪問是更好嗎?一個人,私人人應該是公衆是不是有點奇怪,即使這裏的含義不完全相同。

  2. 當我的IDE對inventory = Collections.synchronizedCollection(new LinkedList());發出警告時,應如何處理該arning?它警告我的類型安全。

謝謝

回答

4
  1. 如果人只在一個封裝中使用,你可以把它違約。否則public是有道理的。

  2. 嘗試給出泛型類型。

    List<Person> people = Collections.synchronizedList(new LinkedList<Person>()); 
    

BTW:大多數IDE將對這些問題之一自動/速戰速決。

2

對於警告,需要指定元素的類型爲LinkedList

inventory = Collections.synchronizedCollection(new LinkedList<Thing>()); 

至於private/publicPerson:如果Person被標記public,這意味着其他代碼(其包裝的另一側)可以根據需要參考/使用它。當您將類型Person成員變量聲明爲private時,表示其他代碼無法直接訪問成員變量。兩者互不影響