English 中文(简体)
如何计算 Java的一般类型?
原标题:How to do calculations on generalized types in Java?

我正在采用多功能系数的通用类别。 我有这一法典:

public class Polynomial<T> {

private HashMap<Integer, T > polynomial;

public Polynomial(T coefficient, Integer index) {
    polynomial = new HashMap<Integer, T>();
    if (coefficient!=0) 
        polynomial.put(index, coefficient);
}

public void sum(Polynomial<T> w) {
    for (Map.Entry<Integer, T> e : w.polynomial.entrySet()) {
        T tmp = polynomial.get(e.getKey());
        if(tmp==null)
            polynomial.put(e.getKey(), e.getValue());
        else {
            polynomial.remove(e.getKey());
            if (tmp+e.getValue()!=0)
                polynomial.put(e.getKey(), tmp+e.getValue());
        }
    }
}

...

}

由于明显的原因,本报告没有汇编。 经营人:=、!=、+、* 和 * 未对通用型T加以界定。 我如何解决这一问题?

问题回答

由于 Java的一般用途与C++不同,你可以使用经营者。 您需要保证<代码>T实施某些接口,并利用接口方法进行计算。 附录一 编号:s methods from T.

您还可以根据与<代码>add(>、mul(>等方法有关的习惯界面,自行开设课程。 由于这些是方法要求,你可以在此使用本土类型,因此大部分的表现已经丧失,因此,在贾瓦的事例中,与C++相比,撰写法典的理由较少。 一些图书馆,如<代码>Trove,实际上使用代号代号代号代号为Java Generics,为一套半标准化的班级获得类似于C++的加工剂类行为。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...