gpt4 book ai didi

Java - 特定泛型实例的实例方法

转载 作者:行者123 更新时间:2023-12-01 14:28:29 25 4
gpt4 key购买 nike

我可以创建一个适用于特定类型的泛型类的方法吗?

例如,我的类(class)如下:

package utils;

public class MyArray<T> {
// Constants
private static final int INITIAL_SIZE = 10;

// Instance Fields
private T[] elms;
private int size;

// Constructor
public MyArray () {
elms = (T[]) new Object[INITIAL_SIZE];
size = 0;
}

// Methods
public void add (T elm) {
if (elms.length == size)
increaseSize();

elms[size++] = elm;
}

@Override
public String toString () {
String str = "[" + elms[0];

for (int i = 1; i < size; i++)
str += ", " + elms[i];

str += "]";

return str;
}

// Helper Methods
private void increaseSize () {
T[] temp = (T[]) new Object[elms.length];
for (int i = 0; i < temp.length; i++)
temp[i] = elms[i];

elms = (T[]) new Object[2 * temp.length];

for (int i = 0; i < temp.length; i++)
elms[i] = temp[i];
}
}

我可以制作一个适用于 MyArray<Integer> 的方法吗?或MyArray<Long>并对其他类型抛出异常?

我尝试执行以下操作:

public T sumOfElms () {
if (T instanceof Integer) {
// code here
}
}

但似乎不起作用。

关于如何做到这一点有什么想法或想法吗?

最佳答案

喜欢@Vishal K解决方案

You can change your constructor in this way:

    public MyArray (Class<T> clazz) {
elms = (T[])java.lang.reflect.Array.newInstance(clazz,INITIAL_SIZE);
size = 0;
}

And while creating the object of MyArray use the following code:

    MyArray<Integer> myArray = new MyArray<Integer>(Integer.class);

你想在泛型类中创建这个非泛型方法,所以你必须采取其他策略,instanceof 很难看。

public T sumOfElms () {
if (T instanceof Integer) {
// code here
}
}

你必须扩展此类才能具有这样的功能(继承或组合)

public class MyLongArray extends MyArray<Long> {

public Long sumOfElms () {
//code here
}

}

或按成分

public class MyLongArrayComposed {

private MyArray<Long> myArray;

public Long sumOfElms () {
//code here
}
}

关于Java - 特定泛型实例的实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16998075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com