Jump to content

Get method using generic types

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
kokokraut

kokokraut

    Newbie

  • Members
  • Pip
  • 4 posts
Hello,

I had a java question about generic types. I am creating a implementation of the List interface using generic types but I was wondering why my get method does not work. (It is just that the return statement in the method generates an incompatible types error).


import java.util.AbstractList;

import java.util.ArrayList;


 class Part8Object<T>{

	

	T item;

	int index;

	public Part8Object(){

		index=1;

	}

	

	public Part8Object(T itemput){

		item=itemput;

		index=1;

	}

	

	public void incrementIndex(){

		index++;

	}

	

}


public class Part8List<T> extends AbstractList<T> {

	

	ArrayList<Part8Object> itemList= new ArrayList<Part8Object>();

	

	

	@Override

	public T get(int arg0) {

		for(int i=0; i<itemList.size(); i++){

			arg0-=itemList.get(i).index;

			if(arg0<=0){

				return itemList.get(i).item;

			}

		}

		return null;

	}


	@Override

	public int size() {

		int sum = 0;

		for(int i=0; i<itemList.size(); i++){

			sum+=itemList.get(i).index;

		}

		

		return sum;

	}


	@Override

    public void add(int index, T element) {

    	if(size()==1 && element.equals(itemList.get(0).item)){

    		itemList.get(0).index++;

    	}

    }

    

    

    public static void main(String[] args) {

	    Part8Object<String> p=new Part8Object<String>();

	    System.out.println(p.index);

    }

}



#2
kokokraut

kokokraut

    Newbie

  • Members
  • Pip
  • 4 posts
Never mind, I actually figured out the problem. It was just that I forget to defined my arraylist of the type part8Object<T>.