Facebook
From das, 5 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 188
  1. interface Ciało <K> {
  2.     K zero();
  3.     K dodaj (K a, K b);
  4.     K mnóż (K a, K b);
  5.  
  6. }
  7.  
  8.  
  9. public class CiałoDouble implements Ciało <Double>{
  10.  
  11.     @Override
  12.     public Double zero() {
  13.         return 0.0;
  14.     }
  15.  
  16.     @Override
  17.     public Double dodaj(Double a, Double b) {
  18.         return a+b;
  19.     }
  20.  
  21.     @Override
  22.     public Double mnóż(Double a, Double b) {
  23.         return a*b;
  24.     }
  25. }
  26.  
  27.  
  28.  
  29. public class Main {
  30.     public static void main (String[] args) {
  31.         CiałoDouble f = new CiałoDouble();
  32.         Wektor<Double, CiałoDouble> v = new Wektor<Double, CiałoDouble>(f, new Double[]{1.0, 2.0});
  33.         v.przemnóżPrzezSkalar(3.0);
  34.     }
  35. }
  36.  
  37.  
  38.  
  39. import java.lang.reflect.Array;
  40. import java.util.Arrays;
  41. import java.util.Objects;
  42.  
  43. public class Wektor <K, F extends Ciało <K>> {
  44.     private K[] x;
  45.     private F f;
  46.     private void alokuj (int rozmiar, K... zbędne) {
  47.         Class<?> c = zbędne.getClass().getComponentType();
  48.         x = (K[]) Array.newInstance(c, rozmiar);
  49.     }
  50.     Wektor(F f) { this.f=f; alokuj(0);}
  51.     Wektor(int n, F f) {
  52.         this.f=f;
  53.         alokuj(n);
  54.         for (int i=0; i<x.length; i++)
  55.             x[i]=f.zero();
  56.     }
  57.     Wektor(F f, K[] a) {
  58.         this.f=f;
  59.         x = Arrays.copyOf(a, a.length);
  60.     }
  61.     Wektor(Wektor<K, F> w) {
  62.         this(w.f, w.x);
  63.     }
  64.  
  65.     @Override
  66.     public int hashCode() {
  67.         //return x.hashCode();
  68.         return Arrays.hashCode(x);
  69.     }
  70.  
  71.     @Override
  72.     public boolean equals(Object obj) {
  73.         if (!(obj instanceof Wektor <?, ?>)) return false;
  74.         Wektor<K, F> v = (Wektor<K, F>) obj;
  75.         if (v==null) return false;
  76.         if (v.x.length != x.length) return false;
  77.         for (int i=0; i<x.length; i++) {
  78.             if (Objects.equals(v.x[i], x[i]))
  79.                 return false;
  80.         }
  81.         return true;
  82.     }
  83.  
  84.     public void przemnóżPrzezSkalar (K a) {
  85.         for (int i=0; i<x.length; i++) {
  86.             x[i] = f.mnóż(x[i], a);
  87.         }
  88.     }
  89. }
  90.  
  91.  
  92.