如何创建类似于C ++模板类的Java类?

时间:2009-12-06 04:18:52

标签: java c++ generics

如何在Java中编写相应的内容?

// C++ Code

template< class T >
class SomeClass
{
private:
  T data;

public:
  SomeClass()
  {
  }
  void set(T data_)
  {
    data = data_;
  }
};

4 个答案:

答案 0 :(得分:39)

class SomeClass<T> {
  private T data;

  public SomeClass() {
  }

  public void set(T data_) {
    data = data_;
  }
}

你可能也想让这个类本身公开,但这几乎就是Java的字面翻译。

C ++模板和Java泛型之间还存在其他差异,但这些都不是您的示例的问题。

答案 1 :(得分:6)

您使用“generics”在Java中执行此操作:

public class SomeClass<T> {
  private T data;

  public SomeClass() {
  }

  public void set(T data) {
    this.data = data;
  }
};

维基百科对generics in Java有很好的描述。

答案 2 :(得分:3)

/**
 * This class is designed to act like C#'s properties.
 */
public class Property<T>
{
  private T value;

  /**
   * By default, stores the value passed in.
   * This action can be overridden.
   * @param _value
   */
  public void set (T _value)
  {
    value = _value;
  }

  /**
   * By default, returns the stored value.
   * This action can be overridden.
   * @return
   */
  public T get()
  {
    return value;
  }
}

答案 3 :(得分:1)

public class GenericClass<T> {
    private T data;

    public GenericClass() {}

    public GenericClass(T t) {
        this.data = t;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    // usage 
    public static void main(String[] args) {
        GenericClass<Integer> gci = new GenericClass<Integer>(new Integer(5)); 
        System.out.println(gci.getData());  // print 5; 

        GenericClass<String> gcs = new GenericClass<String>(); 
        gcs.setData("abc");
        System.out.println(gcs.getData());  // print abc;
    }
}