Question:
Please Halp in JAVA needed !!?
2010-12-21 05:57:51 UTC
I have a class named Student were objects are saved in an ArrayList but I need to convert it to a Treemap or a Hashmap (the easier one is preferred =P).

A student contains the following data members:
- name (String)
- surname (String)
- mark (integer)
- groupNumber (String)
- idNumber (integer)

I need to know how to add, sort, delete, edit and search the Student objects saved in TreeMap or HashMap.

Thank you in advance =]
Three answers:
Chandra
2010-12-21 06:31:09 UTC
Dont ask for a fish. Ask how to fish. That way you will be independent. Find below the code for your question (check for any compilation issues).



Add:

Student s1 = new Student(name, surName, mark, groupNumber, idNumber);

// So on.

Map map = new HashMap() // Change it to TreeMap if you need map.put(1, s1); // Change the key to any value. But int is much easy.





2. For sorting you can use a TreeMap with a comparator.

http://www.java-samples.com/showtutorial.php?tutorialid=370



3. Delete:

Student s1 = null; // s1 is for the input.

int delSt = 0; // for know the key whose value matches. (see below to understand more.)



Iterator it = map.keySet().iterator();

while (it.hasNext()) {

int key = it.next(); // Auto unboxes.

Student st =map.get(key);

if (st.equals(s1)) { // Need to override equals() & hashCode() to tell what to compare.

delSt = key;

}

}



map.remove(key);





3. Edit is easy as you iterate as above and get the Student object value, edit and save it back.

4. Search is as above: iterate and get the value and check if it matches with the given value.



Hope this HELPS! :)



Regards,

Chandra
Malek
2010-12-21 06:07:15 UTC
all the methods for each class are in the java API. Just look it up:

http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html

It doesn't matter if you use the TreeMap or HashMap class since they both implement the Map interface so they have the same set of methods (put, get, remove, etc.)

If you don't know how to use the API, now is a good chance to learn. Every experienced programmer uses the API for whatever language they're using since it's impossible to memorize every single method, class, function, etc in a language.
jeni
2016-06-03 17:10:36 UTC
What is Caesar's Cipher?


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...