在Java Hashtables中返回泛型类型

时间:2015-03-26 16:43:03

标签: java generics

我们目前正在Java课程中学习哈希表。

讲师为我们提出了一些方法来构建。前两个很好,但我正在努力与“公共E max()”。我读过的大多数东西似乎表明你无法实例化泛型类型,所以我很难看到我如何为哈希表编写这个方法。

目标当然是返回哈希表中的最大值,如果类型不是通用的,我认为我可以做,但在这种情况下它是。

如果我的代码有点难以阅读,请道歉。

import java.lang.reflect.Array;
import java.util.*;

public class Assignment6_2015 {
public static void main(String[] args){

//=======================================================
// Question 1, test Point class by creating a hashlist of Point instances       

    HashList<Point> h1 = new HashList<Point>(5);
    h1.add(new Point(1,2));
    h1.add(new Point(2,4));
    h1.add(new Point(2,4));
    h1.add(new Point(2,4));
    h1.add(new Point(3,8));
    h1.add(new Point(3,8));
    h1.add(new Point(7,3));
    h1.add(new Point(9,10));
    h1.add(new Point(9,10));
    h1.add(new Point(9,10));
    h1.add(new Point(9,10));
    h1.add(new Point(9,10));
    h1.displayLists();

//=======================================================
// Question 2, testing new methods

    // ----- Frequency Method Test -----
    System.out.println();
    System.out.print("Frequency of Points (9,10): ");
    System.out.println(h1.freq(new Point(9,10)));

    System.out.println();
    System.out.print("Frequency of Points (2,4): ");
    System.out.println(h1.freq(new Point(2,4)));

    System.out.println();
    System.out.print("Frequency of Points (1,2): ");
    System.out.println(h1.freq(new Point(1,2)));
    // ----- End Frequency Method Test -----

    System.out.println();
    System.out.print("Table Size: ");
    System.out.println(h1.tableSize());
    System.out.print("All used?: ");
    System.out.println(h1.allUsed());
    System.out.print("Percentage used?: ");
    System.out.println(h1.percentUsed());
    }
    }

    //=======================================================
    // class Point
    class Point implements Comparable<Point>{
    private int x,y;
    Point(int a, int b){x = a; y = b;}
    public int x(){return x;}
    public int y(){return y;}
    public String toString(){return "("+x+","+y+")";}

    public boolean equals(Object ob){
    Point p = (Point)ob;
    if(x == p.x() && y == p.y()){
        return true;
    }
    else{
        return false;
    }
}

public int compareTo(Point p){
    if(x > p.x() && y > p.y()){
        return 0;
    }
    else{
        return -1;
    }
}

public int hashCode(){
    return x*y*31;
    }
}
   //End class Point
  //=======================================================
  //HashTable class
  class HashList<E extends Comparable<E>>{
  private GLinkedList<E> data[];
  public HashList(int n){
    data = (GLinkedList<E>[])(new GLinkedList[n]);
    for(int j = 0; j < data.length;j++)
        data[j] = new GLinkedList<E>();
}
private int hashC(E x){
    int k = x.hashCode();
    //an alternative is to mask the minus using
    //int k = x.hashCode() & 0x7fffffff;

    int h = Math.abs(k % data.length);
    return(h);
}

public void add(E x){
    int index = hashC(x);
    data[index].add(x);
}

public boolean contains(E x){
    int index = hashC(x);
    return(data[index].contains(x));
}
public void displayLists(){
    for(GLinkedList<E> k : data){
     if(k.length() > 0)
          k.display();
    }
}
public void display(){
    System.out.print("<");
    int ind = 0;
    while(ind < data.length){
        Iterator<E> it = data[ind].iterator();
        while(it.hasNext())
            System.out.print(it.next()+" ");
        ind++;
    }
    System.out.println(">");
}
public int tableSize(){
    return data.length;
}
//===================================================================
//Add new methods for assignment here

public int freq(E x){
    int freq = 0;
    int index = hashC(x);
    for(int j = 0; j < data[index].length();j++){
        if(data[index].contains(x)){
            freq++;
        }
    }
        return freq;
}

public boolean allUsed(){
    int total = data.length;
    int inuse = 0;
    for(int j = 0; j < data.length;j++){
        if(data[j].length() >= 1){
            inuse++;
        }
    }

    if(inuse == total){return true;}
    else{return false;}
}

public E max(){
    int j = 0;
    E y = // ???;
    Iterator<E> it = data[j].iterator();
        while(j<data.length){
            it = data[j].iterator();
            E x = it.next();
            while(it.hasNext()){
                if(data[j].iterator().next().compareTo(x) == 0){
                    x = it.next();
                    y = x;
                }
            }
        j++;
        }
    return y;
}

//int x = (it.next().compareTo(largest));
//if(x == 0){largest = it.next();}




//====================================================================
public double percentUsed(){
    int count = 0;
    for(int j = 0; j < data.length; j++){
        if(data[j].length() > 0)
          count++;
    }
    double p = count *100.0 / data.length;
    return p;
}
public int largestBucket(){
    int max = 0;
    for(int j = 0; j < data.length; j++)
        if(data[j].length() > max) max = data[j].length();
    return max;
}
public int smallestBucket(){
    int min = data[0].length();
    for(int j = 1; j < data.length; j++)
        if(data[j].length() < min) min = data[j].length();
    return min;
}
public int[] listSizes(){
    int n = this.largestBucket();
    int d[] = new int[n+1];
    for(int j = 0; j < d.length; j++) d[j] = 0;
    for(int j = 0; j < data.length; j++){
        int m = data[j].length();
        d[m] = d[m] + 1;
    }
    return d;
}
public int empty(){
    int count = 0;
    for(int j = 0; j < data.length; j++)
        if(data[j].length() == 0) count++;
    return count;
}
public Iterator<E> iterator(){
  ArrayList<E> items = new ArrayList<E>();
  int ind = 0;
  while(ind < data.length){
        Iterator<E> it = data[ind].iterator();
        while(it.hasNext())
            items.add(it.next());
        ind++;
   }
   return items.iterator();
}
}
class GLinkedList<E extends Comparable<E>>{
private Node<E> head = null;//empty list
private int size = 0;
public void add(E x){ //add at head
    Node<E> nw = new Node<E>(x);
    nw.setNext(head);
    head = nw;
    size++;
}

public boolean contains(E x){
    Node<E> k = head;
    boolean found = false;
    while(k != null && !found){
        E kk = k.data();
        if(kk.compareTo(x) == 0) found = true;
        else k = k.next();
    }
    return found;
}

public void remove(E x){
    Node<E> k = head; Node<E> bk = head;
    boolean found = false;
    while(k != null && !found){
        if(k.data().compareTo(x) == 0) found = true;
        else{ bk = k; k = k.next();}
    }
    if(found)
        if(k == head)
            head = k.next();
        else
          bk.setNext(k.next());
}

public int length(){
    return size;
}
public void display(){
    Node<E> k = head;
    System.out.print('[');
    while(k != null){
        if(k.next != null)
           System.out.print(k.data()+", ");
        else
           System.out.print(k.data());
        k = k.next();
    }
    System.out.println(']');
}
public Iterator<E> iterator(){
    return new GIterator<E>(head, size);
}
     private static class GIterator<E extends Comparable<E>> implements Iterator<E>{
    private Node <E> head;
    private int size;
    private int index = 0;
    GIterator(Node<E> h, int s){
        head = h; size = s;
    }
    public boolean hasNext(){
        return index < size;
    }
    public E next(){
        if(index == size) throw new NoSuchElementException();
        E item = head.data();
        head = head.next(); index++;
        return item;
    }
    public void remove(){}
}
}
class Node<E extends Comparable<E>>{
E data;
Node<E> next;
public Node(E  x){
    data = x; next = null;
}
public Node<E> next(){return next;}
public void setNext(Node<E> p){
    next = p;
}
public void set(E x){data = x;}
public E data(){return data;}
}

目前,max()方法不起作用,我已经尝试了一些内容,但无论我采用何种方式,我都无法让它返回泛型类型。

4 个答案:

答案 0 :(得分:0)

为什么不写这个

E y=null;

答案 1 :(得分:0)

要稍微清理代码,帮助降低复杂性并避免错误,您可以使用此代码段迭代所有元素

for ( GLinkedList<E> d : data ) {
  final Iterator<E> it = d.iterator();
  while ( it.hasNext() ) {
    final E currentElement = it.next();

    // Insert logic here!

  }
}

答案 2 :(得分:0)

Point类实现Comparable,由于HashListComparable对象组成,您可以使用此属性来比较每个Point作为Comparable

max()的逻辑如下:

declare max as a `Comparable` 
for each linked-list `ll` in `data`
   for each element `c` in `ll`
      if `c.compareTo(max) >= 0` then
         max <- c
      endif
   endfor
endfor
return max

你必须处理max初始化到null或哈希表中的第一个点,或者总是次等到某个点的某个点值,比如Point(Integer.MIN_VALUE, Integer.MIN_VALUE)

答案 3 :(得分:0)

您可以通过以下方式在max方法中编辑这两行:

E y = (E)data[0]; // ???;
int j = 1;

以上代码更改将解决您的问题。此外,您还必须在评论中添加上面提到的其他空检查等。 像

if(y==null) return null; //since there is no element in the array