Jump to content
SubSpace Forum Network

Recommended Posts

Posted

OKay, so I know a few Java programmers frequent here, so I've got a small question.

 

The following code constructs an 'IdentityCard' with both get and set methods (I've not included the set methods)...

 

public class IdentityCard {
private String title;
private String forename;
private String surname;
private String idNumber;
private String dept;
private String idContact;

public IdentityCard(String title, String forename, String surname, String idNumber, String idContact, String dept) {
	this.title = title;
	this.forename = forename;
	this.surname = surname;
	this.idNumber = idNumber;
	this.idContact = idContact;
	this.dept = dept;
}

/* Get Methods for IdentityCard */
public String getTitle() { return title;}
public String getForeName() { return forename;}
public String getSurName() { return surname;}
public String getStudentID() { return idNumber;}
public String getDept() { return dept;}
public String getContact() { return idContact;}

 

I'll be creating an instance of IdentityCard with

 

IdentityCard card = new IdentityCard (title, forename, surname, idNumber, dept);

 

Then, each instance of card will be placed into a LinkedList. The problem I've run into is I need to then pull that instance of card from the LinkedList and make sense of it (when it's in a linkedlist it's just an object).

 

I understand that I'll need to create a toString() method of some kind, but I'm not sure exactly how to do that. I've tried a few approaches, but this is the third programming assignment I've done today... and honestly, I can't be bothered.

 

Any hints/tips would be hugely appreciated. :D

 

The assignment is very incomplete, and I still need to format the code in a better way but you can view the full source code here:

 

RegistrySystem.java

 

IdentityCard.java

 

Been up for 28 hours now. Time for a little sleep.

Posted

I'm not sure what you're looking for here... what's your question?

 

You're right, you should always provide a toString() method for your class; it's such a pain to debug code when you see something like this "IdentityCard@46c20a1".

 

The question is, do you just provide general accessors to piece the information together?

 

public String getFullName() { return surname + ", " + forename; }
public String getMailingAddress() { // piece together name(s) + address + city + state + ... }

 

Then in the toString() use these accessor methods to generate the toString() method... it's really up to you.

 

A class is nothing by itself .. here are a couple of examples of how to use this class...

List<IdentityCard> listOfIdentityCards = new ArrayList<IdentityCard>();
listOfIdentityCards.add(new IdentityCard(...));


// iterate over each card in the collection
for (IdentityCard currentIdentityCard : listOfIdentityCards) {
   if (currentIdentityCard == null) continue;   // for safety sake... you don't "need" this; but.. i'm paranoid about NullPointerExceptions
   System.out.println(currentIdentityCard);
}

 

I won't go on too much about "enterprise" java approaches, but, you likely wouldn't see a class with constructor parameters (really, 6 parameters?) ... :D They'd just have a POJO (plain ol java object) .. every attribute has a getter and setter. You'd then have another class "build" the IdentityCard object based on information which is passed to it.

Posted

Thanks for the answer, that's exactly what I was looking for. :D

 

So with that in mind, what would be the best method for finding/deleting IdentityCard objects from the ArrayList? I looked at the Java API and contains() looks like it's what I should be using but I'm not sure. Here's what I was thinking...

 

for (IdentityCard currentIdentityCard : IdentityCards) {
if (currentIdentityCard == null) continue;
   if (currentIdentityCard.contains(idNumber) = 0) {
   	System.out.println(currentIdentityCard);
   	IdentityCards.remove(currentIdentityCard);
   	System.out.println("Card was successfully removed from the registry");

 

Also, I'll need to save the ArrayList into a file, and read it from a file. I started reading up on how to do this, but I've not had a chance to finish it yet.

 

public void storeData() {

Path file = "Card.dat";
try {
   		file.createNewFile();
} catch (FileAlreadyExists x) {
   		System.err.format("file named %s already exists%n", file);
   		openFile();
} catch (IOException x) {
   		System.err.format("createFile error: %s%n", x);
} // possibly include canWrite(); as further validation..

}

 

OKay, the best way to handle this seems ObjectOutputStream what do you think?

Posted

This post may not make sense since I'm staying up way too late - so I apologize. :)

 

First, the contains() method on the List interface says the implementation must "Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e))." The equals method on the class Object and can be overridden, but, there are *hazards* to that - and probably are not recommended (if you really need to get those edge cases, read Effective Java 2nd Edition, by Joshua Bloch; ISBN 978-0-321-35668-0).

 

Based on your comments I don't think the equals() method is what you're looking for since you can't tell me under what conditions will two IdentityCards equal() methods match.

 

Lists tend to be preferred if you have a set of data without a particular order and you need to insert/remove quickly. You generally sacrifice time "looking" for your object unless you know what index the object is located at (simple call: myList.get(index#)).

 

You may need to use a Map (via HashMap implementation)... Maps are helpful when you are able to identify a 'key' value to pull up a 'value'. With Java 5+ you need to specify the class-types being held within the Map structure. Remember, a Map is a 1-to-1 relation so if you insert a value with a duplicate key, you may overwrite the existing value.

 

1->objectA

2->objectB

3->objectC

1->objectD (this would overwrite "objectA")

...

 

Here are a couple of examples:

(a)

A map containing an Integer as the key value which is related to a specific IdentityCard.

Map<Integer, IdentityCard> setOfIdentityCards = new HashMap<Integer, IdentityCard>();

 

To iterate:

for (Integer key : map.keySet()) {
   // ...
}

 

(:D Or, a map with a key type of "String" where the value related to a specific IdentityCard. I'm only mentioning it as a possibility (I would probably avoid using it).

"Smith, J"->objectA

"Doe, J"->objectB

...

Map<String, IdentityCard> setOfIdentityCards = new HashMap<String, IdentityCard>();

 

To iterate:

for (String key : map.keySet()) {
   // ...
}

 

 

Or to get both the Key and Value at the same time during iteration (most common scenario)...

 

for (Map.Entry<Integer, IdentityCard> entry : map.entrySet()) {
   String key = entry.getKey();
   IdentityCard value = entry.getValue();
   // ...
}

 

Example, assuming you have an Integer called int myKeyValue = 1;...

To add:

thisIsMyMap.put(myKeyValue, new IdentityCard(...));

To remove:

thisIsMyMap.remove(myKeyValue);

.

 

I'd encourage you to reference Map API or HashMap documentation for more details. Don't read these pages as a book - but use them to help you figure out what's going to happen with your code when you execute it. :)

 

You're touching one of many aspects of programming where there is no "right" answer because it all "depends" (based on whether the data can it be catagorized, how many records, how often is it being called, will it be used in a multi-threaded application, etc.). You learn when to use a particular data structure for the task at hand by experience and tinkering.

 

Edit: I forgot about the second part of your question regarding the serialization (storing) of IdentityCards. I have intentionally used it in 1 assignment because I was running out of time and didn't feel like coding up a different solution of storing values someplace (a text or XML file as an example). Most other times my data is stored/read from a database or network source where my data is given to me in an XML String structure which I have to parse and build into objects from scratch (oh the joy *sarcastic*).

 

(To any of the Java developers who may be reading this and use serialization for RMI - you'll have to let me know how that's working for ya. :))

Posted

Thanks again, I decided to avoid the use of hashmaps because I've got a lot of other studying and didn't really feel like looking up on those methods, so instead I took the following approach to finding/deleting cards:

 

public void delCard() {

System.out.print("Please enter the student identification number:> ");
idNumber = scan.next();

for (IdentityCard currentIdentityCard : IdentityCards) {
   	if (currentIdentityCard == null) continue;
	String tempValue;
	tempValue = currentIdentityCard.getStudentID();
	if (tempValue.equals(idNumber)) {
		System.out.println("Card was successfully found in the registry: ");
		System.out.println(currentIdentityCard.toString());
		System.out.print("Are you sure you want to delete? [Y/N]");
		userInput = scan.next();
		if (userInput.equalsIgnoreCase("Y")) {
			System.out.println("Card was successfully removed from the registry");
			IdentityCards.remove(currentIdentityCard);
		}
		if (userInput.equalsIgnoreCase("N")) {
			continue;
		}			
   		else
		System.out.println("The identification card was not found in the registry");
	}
System.out.println("Returning you to the Main Menu...");
Welcome();
}
}

 

I'm going to fiddle with a few ways of saving the ArrayList to a .dat file, and I'll let you know how things go. Thanks again for the assistance. :D

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...