-2

I know it's generally not a good thing to bring up homework assignments on a website such as this. I am not asking for handouts, nor do I wish anyone to finish anything for me. I said this at the beginning because you never know, someone on here may have had this same assignment. I don't want to be seen as a cheater or in any way relying on this community to complete my homework assignments like a spoiled child. I just sincerely love to program, and I am dying to understand more about it.

I aim merely to understand Generics, and how I can use this to benefit my algorithms. I am a Sophomore in a Data Structures class, and the professor wants us to create a program that creates Key, Value pairs. These key value pairs are individual objects that are created from books such as Tom Sawyer. Each unique word is a key, then the value represents how many times this unique word appeared in a text. He says every Key would be a String, and every Value would be an Integer. Eventually we will have to analyze these books and compare them to each other. I knew that this would require an array of Pair objects. It was simple enough to create the Pairs.

I understand this much, and I was able to successfully create and print these Pair objects without using Generics. However the project gets more complex. I need more then one array and these Pairs wont have an integer as a Value but a Double so that I can find the frequency of words, so I have realized that continuing without using Generics will result in more code than necessary. Others are doing it without Generics but my professor constantly makes remarks that "they are making their life harder for no reason". In all of my previous programming classes there was a lab to accompany them, and we had hands on experience when it came to learning about code. In those classes there was no mention of anything called generics.

So naturally, I want to make my life easier. I want to understand and use this thing called generics, that I have never seen before.

Many other individuals are having trouble with the current assignment, and I have presented my code to tutors and the professor himself. I have sent emails and etc. I have literally tried every avenue I can think of. I have read the Oracle Doc such as this

https://docs.oracle.com/javase/tutorial/java/generics/types.html

But the example here is nowhere near specific enough to help me in my case, either that or the point is just flying right over my head.

He has even extended the deadline for the assignment a whole week, because he was receiving so many emails regarding how to do this.

But no matter who I see, or what they suggest I always end up staring at my code that just refuses to compile. It gives me errors that say "generic array creation", but I am not sure why I can't create this array. I have read many people suggest to not use Arrays, but instead use ArrayList. However the issue is that my professor doesn't want us to use ArrayList. He wants us to essentially build our own. For example I named mine arrayPair.

I have created a generic Pair class. As suggested by him. I have created the generic arrayPair class. This class is really the one that seems to refuse to compile. I have a Driver class which contains the main function, this uses the Scanner and StringTokenizer with delimiters to retrieve all the individual words. I then convert them to lowercase.

And I also have a interface that I named Dictionary

Here is the dictionary interface:

public interface Dic<K,V>

{

    void set(K key, V value);
    void remove(K key); 
    void reset();
    boolean isFound(K key);
    void next();
    K getCurrentKey();
    V getCurrentValue();
    void changeValue(V value);
}

So this compiles, and all is fine.

So far I know what generics do, and why they are useful(at least I think). They allow you to implement the same code in many different ways. You can specify what these "types" are later on, and they can be a String, Integer, or whatever you wish, even objects as well. My professor said that generics will work with integers, strings, and also doubles. But then I do some reading around the internet and I then see this.

http://www.tutorialspoint.com/java/java_dictionary_class.htm

I notice notice that the key and value are objects. Not a String or Integer.

Then I see this:

Why don't Java Generics support primitive types?

So wait a second, Java Generics doesn't support primitive types? So what is my professor talking about?

Also many of the examples or solutions provided on this website use the ArrayList, then I get disappointed because that is exactly what I was told NOT to use.

So perhaps I am missing something very simple, and just the notion of that drives me crazy.

I guess all I can do is provide to you good people, my arrayPair class as it is.

I have changed the way I write the syntax of lines 22 and 40 so many times it's crazy. I've stared at this thing for HOURS. Please note that some of these fields are just there because I was screwing around with different ideas for a while. Some are just useless fields. The error shows up on line 11 and 21 (not including white lines).

public class arrayPair<K, V> implements Dictionary<K, V>
{

    private int capacity = 100; //Default capacity for pair array.

    private int card = 0;

    private Pair reference; //Used to store referenceerence to an array slot.

    private int iterator = 0; //Used to iterate through the array.

    private String currentKey;

    private double currentValue;

    private boolean contains;

    private boolean stop;

    arrayPair[] pairs = new Pair<K,V>[capacity];

    private K key;

    private V value;

    private String temp;

    @SuppressWarnings("Unchecked") // I added this because I saw it around online, no idea if it is needed. Or what it dooes. 

    @Override 
    public void set(K key, V value)
    {
        K k = key;
        V v = value;

        Pair<K, V> pa = new Pair<K, V>();
        reference =pa;

        if(card == (capacity)-1)
        {
            doubleSize();
        }    
        if(!this.isFound(key)){

            pairs[card] = pa;
            card++;
            reset();
        }
        else{
            reference.increaseValue();
            reset();
        }
    }

Any help or insight is much appreciated. Just nudge me in the right direction, how in the world should I approach this using Generics? What does it even look like? Then I have seen on this website, that you cast things to an object, I was never told this in my previous classes. So I don't know the syntax required, nor do I know if it is necessary in my case. I also don't see how it can create objects when no class is present to represent them. I have just become so incredibly confused during this semester, but last semester I crushed it. I figured this post is already way to long, so I didn't want to add my other classes. If you need to see the Pair class as well I can provide it. But it is written exactly like I was told it should be. It compiles as well, but to increase the value of Value by 1 is impossible. It says that "the binary operator + 1 cannot be applied to type V".

So something is going on with Generics and the use of Primitives. I just don't understand what. Hell I don't know what to believe anymore!

EDIT:

Here is the Pair class as requested.

    public class Pair<K, V>
{

public K key;

public V value;

public Pair(K k, V v)
{
    this.key=k;
    this.value=v;
}

public K getKey()
{
    return this.key;
}

public V getValue()
{
    return this.value;
}

public void setValue(V v)
{
     this.value = v + 1;
}

public String toString()
{
    String statement = ("Key: " + this.key + " " +"Value: " + this.value);

    return statement;
}

}
Community
  • 1
  • 1
  • 2
    I would recommend you quit this course. Your instructor is probably brain dead and the cancer could infect your own brain. – emory Oct 16 '15 at 01:51
  • 5
    Welcome to Stack Overflow, @EdwardJenkins! I just wanted to say that this is a *really long* post and I feel like you could shorten it a little to make it easier to understand (you don't have to explain the *entire* program and goal. Just say that you're just looking for an example for generics)... – Jonathan Lam Oct 16 '15 at 01:52
  • 3
    Congratulations, you just finished your term paper :-) – Tim Biegeleisen Oct 16 '15 at 01:52
  • Oh man... I'm not quite sure how to respond to this. This is terrifying man. D: Like I've spent thousands of dollars on starting this semester at this University. I also really apologize for it being so long, I just wanted it to be clear what my code was supposed to do. As obviously my code is not clear at all.... Oh this is just a mess man. – Edward Jenkins Oct 16 '15 at 01:52
  • What is the exact error message? I think that would help to answer this best. And also, where is the `Pair` class? I can't seem to find it (except in `javafx.util` and in `org.apache.commons.lang3.tuple`, which I don't think you're looking for) – Jonathan Lam Oct 16 '15 at 01:53
  • @jlam55555 it just says "generic array creation" which is of no use to me. I also use the IDE BlueJ, because that is what they started me on. I just went to eclipse like an hour ago. – Edward Jenkins Oct 16 '15 at 01:56
  • @EdwardJenkins my comment was not meant as a criticism of you. I feel that you are not getting value for your thousands of dollars. The assignment seems low quality to me. – emory Oct 16 '15 at 02:00
  • @emory I understand this, and it eats me up honestly. I've had many other friends drop out (like more then 5). Some even switched majors. The Withdraw deadline has not been reached yet. If I can't figure it out.... I might Withdraw.... But I spent so much money... I just almost HAVE to persevere through this. I have to learn.... and quickly... you know? The last test he gave, everyone failed. He also put things on the test that we didn't cover, and fully admitted to that. This course just... I love programming so I refuse to let this stop me on my path. – Edward Jenkins Oct 16 '15 at 02:05
  • @EdwardJenkins Don't freak out. It's a simple programming question. Someone on this site (there are millions of pros here) will solve your problem. **It'll be all right** – Jonathan Lam Oct 16 '15 at 02:06
  • 1
    @jlam55555 I mean... I'm not like losing my sanity or anything. Just trying to save several hundred bucks, and not withdraw from the course. I've honestly been afraid to ask on this site, I thought people would tell me this is easy. Or that I am just not good at programming. At the end of the day, I can always withdraw and take this course next semester with another professor. But I thought maybe StackOverflow contains the people who can help me avoid withdrawing. Maybe I can go back and show this professor what I'm made of right? – Edward Jenkins Oct 16 '15 at 02:10
  • Possible duplicate of [Java noob: generics over objects only?](http://stackoverflow.com/questions/3015716/java-noob-generics-over-objects-only) – michaelsnowden Oct 16 '15 at 02:16
  • @EdwardJenkins I edited my post. I hope it helps some more. – Jonathan Lam Oct 16 '15 at 02:17
  • "I just sincerely love to program"--why are you including this? – michaelsnowden Oct 16 '15 at 02:17
  • @michaelsnowden I assumed that some users would attempt to say that I don't really wish to learn, but to have others just complete stuff for me. I just wanted to avoid be berated by angry internet users. I apologize if it came off strange... It made sense at the time. – Edward Jenkins Oct 16 '15 at 02:24
  • @michaelsnowden also the example you linked discusses maps. Nothing to do with Generic Objects in arrays. Which is my current issue. – Edward Jenkins Oct 16 '15 at 02:46
  • @EdwardJenkins It doesn't matter if it's an array or a map. The problem is the same. – michaelsnowden Oct 16 '15 at 03:03
  • The issue is not creating the generic objects, it's storing them in the Generic Array. At least I think that is the issue. I even stated in other comments to answers, that I tried changing to I was still presented with the same error saying "generic array creation" The issue is not the same. At least as far as I can tell. Sorry if I'm to "stupid" to understand the linked post. But to me it doesn't seem to solve my issue. Plus I've already tried what it suggests. I've been experimenting with this code for DAYS. Its not like I just didn't simply replace K with String. – Edward Jenkins Oct 16 '15 at 03:17

3 Answers3

1

Regarding objects/primitives, your course seems to be based in Java 1.4, but you're using a higher version? If so see auto-boxing/unboxing

The data structure you need is not an array but a map.

You seem to have a hint with java.util.Dictionary so look at implementation of Hashtable, better yet Map.


Note:

@SuppressWarnings("Unchecked") // I added this because I saw it around online, no idea if it is needed. Or what it dooes.

Doesn't tie with:

I just sincerely love to program, and I am dying to understand more about it.

Especially with goole/SO: What is SuppressWarnings ("unchecked") in Java?

Community
  • 1
  • 1
earcam
  • 6,522
  • 3
  • 33
  • 55
  • "The data structure you need is not an array but a map" I was told to use arrays. Sorry I forgot to google the unchecked warning, I was googling generics. Meany. – Edward Jenkins Oct 16 '15 at 02:22
0

Not a complete answer for you, but i realized you're asking like 15 different questions so i'll try to clear your brain a bit.

My professor said that generics will work with integers, strings, and also doubles.

That is correct. For example List<Integer> list = new ArrayList<Integer>() or List<Double> list = new ArrayList<Double>() are valid. Integer and Double are the object wrapper types of the primitives int and double. Generics can only be used with Objects because it gets turned into a type cast.

But then I do some reading around the internet and I then see thisI notice that the key and value are objects. Not a String or Integer..

String and Integer are Object. Object is the GOD of Java, every type derives from Object.

Then I see this: Why don't Java Generics support primitive types? So wait a second, Java Generics doesn't support primitive types? So what is my professor talking about?

Correct. Try putting this in Java, List<int> list = new ArrayList<int>(). You'll get a compile error. Why? because Generics only work with Objects, and not primitives. For int, you use Integer, for double, you use Double, for char, you use Character, etc.

To try and point you in the right direction, your class arrayPair<K,V> expects 2 types at run time, K and V. In the context of your assignment, K would be String, and V would be Double. K is a unique word in the Tom Sawyer text, and V is the Double that counts the words occurence.

I'll try to show you how Generics are useful. Let's say you instantiate arrayPair as arrayPair<String,Double> test = new arrayPair<String,Double>(). Pretend there is a method called foo(K var, V var2). Once you instantiate arrayPair, foo expects a String for var, and a Double for var2. If you try to call foo(5,5), you're program isn't going to work, because it expected a String and Double, but you gave it 2 ints. Does that make sense?

One last tip, you must declare Generics with Objects, but you can do operations with primitives if its the correct wrapping class. What i mean by that is, you create a List that contains Integers, so List<Integer> list = new ArrayList<Integer>(), now you can add an int to this list. list.add(5). This is autoboxing/unboxing feature of Java.

Eric Guan
  • 13,320
  • 7
  • 34
  • 53
  • I would love to use ArrayList. I was told specifically not to. Also when I created these generic objects. I experimented with putting instead of I still got errors. – Edward Jenkins Oct 16 '15 at 02:28
0

I just found this link that says,

You can't have arrays of generic classes. Java simply doesn't support it.

You should consider using a collection instead of an array. For instance,

public static ArrayList<List<MyObject>> a = new ArrayList<List<MyObject>();

Another "workaround" is to create an auxilliary class like this class MyObjectArrayList extends ArrayList<MyObject> { } and then create an array of MyObjectArrayList.

Since your instructor is not letting you use ArrayList, I guess you'll find this more difficult.

You could use a non-generic Pair (e.g. arrayPair[] pairs = new Pair[capacity];), but this would undermine your original intent to use generics.

If you're allowed to use HashMap or other iterative types in Java, use those instead, I guess. That's my best advice.

I hope this helps.

Community
  • 1
  • 1
Jonathan Lam
  • 15,294
  • 14
  • 60
  • 85
  • The version I had, before trying to use generics. Does exactly what you suggested with: arrayPair[] pairs = new Pair[capacity]; And I got it to work, but there is so much more coding to do then. And he says using generics is the way to go, and it will save me so much effort. I mean the guy has a PhD so I assume he knows what he's talking about.... He just says this without providing an actual example. – Edward Jenkins Oct 16 '15 at 02:56