I am currently learning about generics in Java, coming from C++ it's quite a difference. I'd like to a vector addition, in C++, it would look something like this. (I know that this code is not well-written, it's just for a quick example to show what I want to do)
#include <iostream>
#include <vector>
template <typename T>
class Vect{
public:
std::vector<T> vect;
Vect(std::vector<T> t){vect = t;}
T index(int i){return vect[i];}
void print(){
for(int i = 0; i < vect.size(); ++i){
std::cout << vect[i] << " ";
}
std::cout << std::endl;
}
void add(Vect<T> other){
for(int i = 0; i < vect.size(); ++i){
vect[i] = vect[i]+other.index(i);
}
}
};
int main(){
std::vector<int> p1;
p1.push_back(1);
p1.push_back(2);
p1.push_back(3);
p1.push_back(4);
Vect<int> vec1 = Vect<int>(p1);;
Vect<int> vec2 = Vect<int>(p1);;
vec1.print();
vec2.print();
vec1.add(vec2);
vec1.print();
return 0;
}
I am trying to do the same with Java but I can't get a way to add two generics T and put the value (a T) in the first vector. I am doing this :
public class Vect0<T extends Number> {
//Attributs
private T[] _vec;
//Constructeur
public Vect0(T[] vec){
System.out.println("Construction du _vec !");
_vec = vec;
}
//Getter
public int get_length() {
return _vec.length;
}
//Methodes
public void print(){
System.out.print("[");
for (int i = 0; i < _vec.length; ++i){
if (i != _vec.length-1) {
System.out.print(_vec[i] + ", ");
}
else {
System.out.print(_vec[i]);
}
}
System.out.println("]");
}
public T index(int i) {
return _vec[i];
}
public void sum(Vect0<T> other) {
if (other.get_length() == this.get_length()) {
for(int i = 0; i < this.get_length(); ++i) {
Double res = (this.index(i).doubleValue() + other.index(i).doubleValue());
System.out.print(res);
T t = (T) res;
_vec[i] = t;
}
}
}
}
So it does print a double, but then the casting doesn't work and I get an error :
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Double at Vect0.sum(Vect0.java:37) at Main.main(Main.java:12)
I hope you can help me figure this out. Thank you very much.