【问题标题】:How to fix this warning?如何解决此警告?
【发布时间】:2012-06-14 08:25:42
【问题描述】:

我正在为 Persons 开发一个课程,我有一两个关于它的问题。

/**
 * 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 类应该是公共的还是默认访问更好?一个Person,一个privatePerson 应该是public,这不是有点奇怪,尽管这里的意思并不完全一样。

  2. 当我的 IDE 警告 inventory = Collections.synchronizedCollection( new LinkedList() ); 时,我应该如何处理这个问题?它警告我的类型安全。

谢谢

【问题讨论】:

    标签: java model-view-controller model game-engine


    【解决方案1】:

    对于警告,您需要为LinkedList指定元素的类型:

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

    至于private/public 对于Person:如果class Person 被标记为public,这意味着其他代码(其包的其他部分)可以引用/使用根据需要。当您将Person 类型的成员变量 声明为private 时,意味着其他代码无法直接访问该成员变量。两者互不影响

    【讨论】:

      【解决方案2】:
      1. 如果 Person 只在一个包中使用,您可以将其设为默认值。否则public 有意义。

      2. 尝试给出泛型类型。

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

      顺便说一句:大多数 IDE 将自动/快速修复这些问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-07
        • 2013-04-29
        • 2011-12-03
        • 2015-09-11
        • 2012-01-05
        • 2011-04-09
        • 1970-01-01
        相关资源
        最近更新 更多