|
Friday 2024-11-15 5:09 AM |
CHAT | |
Statistics |
Total online: 3 Guests: 3 Users: 0 |
VISITORS | A HEARTY WELCOME TO MA VISITORS 4R ENTERIN MA BLOG
THNX 4R VISITIN MA BLOG |
|
|
Welcome Guest | RSS
Main | Registration | Login |
STUDENTS QUEST |
Main » 2011 » August » 08
In this tutorial, we will be covering how to use Classes and Objets instead of Parallel Arrays. In order to teach students how to use arrays, many instructors give assignmentsallows students to gain confidence when using arrays, this type of approach becomes very cumbersome to use and difficult to manage, especially as the number of elements stored increases in size and more so as the use of resizable collections like ArrayLists come into play.
So let's go ahead and start out with a standard inventory program that uses parallel arrays to store price, quantity and name. This program will display a menu using a JOptionPane window requesting input for adding inventory, updating a current item's status, displaying the inventory, and quitting. If the user wants to update an item, we will display another menu asking for the index of the item to change. After we recieve the index, we will display another menu asking the user if they want to update the name, quantity or price, followed by a prompt for the new value. And as was the requirement when I did the assignment, we'll limit the size of the arrays to 10 items in inventory. So far, this program isn't too bad. A few tedious things (beyond getting input) that I noticed included making the display String for a given item, like at this line String item = "Name: " + name[index] + "\nQuantity: " + quantity[index] + "\nPrice: " + price[index];. Consider this though- what would happen if there were no size limitations as to the number of items you could have in inventory (meaning we are now using ArrayLists in parallel instead of static arrays)? When you go to add or remove (which would be the next logical step) items, you wouldn't have to use a counter variable because the ArrayLists would automatically resize as soon as elements are added or removed from them. This gets a little sticky, however, when removing elements in the middle of the lists, as it is very easy to get attributes mixed up. For example, you could remove element 9 for the name list, but end up removing element 8 from the quantity and element 10 from the price list. This would completely mess up the data integrity and accuracy, plus it is very hard to debug this error.
Another logical step would be to sort the elements according to one of their attributes (name, quantity or price). Using parallel arrays, you have to enforce each step of the sort amongst all three arrays. So for example, if you sort the quantity array in ascending order, the changes aren't automatically affected throughout the other two arrays. This means that if you call Arrays.sort() on one array, it doesn't necessarily change the other two. And if you call Arrays.sort() on each of the three arrays, you have just sorted three arrays individually, so your name, qunatity and price array are all in order according to the values stored in them. However, you will have mismatched all the attributes from the item they are supposed to describe.
Now that we've seen the cons of parallel arrays, let's talk about the advantages of using classes instead. First off, the attributes representing each class are contained within the class. This means that the quantity, price and name cannot get mismatched like we saw when using parallel arrays. This also means that we only have to manage one collection, so it saves memory. Next, we can use methods to make our lives easier. This means that we can set up a toString() method in the class, and when invoked, it will return a nice formatted (to our specifications) String; and we can also use a single setter method so we can eliminate the group of if statements for updating an item. So in short, you are dealing with one variable that holds all the information and can have automated tasks set up instead of having to hard code each component as we saw above.
Now that we've discussed the advantages of classes, let's take a look into puttingputting them into use. To start, we'll take a look at designing a class to model an Item. After looking at the Item class, I notice how it is a lot more organized than using parallel arrays, plus it provides a little tighter control on the attributes and more usability through many of its methods, most notably the toString() and update() methods. Now let's redo our Inventory program using the Item class instead of Parallel arrays. As we can see, this program gives us tighter control over each Item because we don't have to worry about keeping up with which indices represent each Item. This becomes increasingly important as we move onto using resizable collections like ArrayList, and as we attempt to sort the Items by a given attribute (or multiple attributes). We also have the convenience of using methods defined in the Item class, something we didn't have the luxury of doing when using parallel arrays. By using classes instead of parallel arrays, you will begin to get a better handle on Object-Oriented Programming. This will help you as you continue your studies of Java, especially as you come across more advanced OO concepts like inheritance, abstraction and polymorphism, in addition to helping you better organize your program.
|
The one thing I can emphatically say iMOVING AWAY FROM PARALLEL ARRAYS . Use classes and objects instead! They will help you organize your code so much better, as well as develop modular and reusable components.
I would also encourage developers to use appropriate data structures. When choosing a data structure, using it should make your life easier, especially as the size of the problem grows. The structure should also provide an efficient and appropriate means of accessing data (ie., with Trees, it might take longerr to traverse the Tree, but it shouldn't take O(n^3) time to access a bottom-level element in the Tree). Some examples of appropriate data structures are Maps for finding the frequencies of occurrences for elements, Graphs for GPS systems, etc.
Regarding GUIs, always separate your GUI from your data and program state. Regardless of the UI (console, GUI, etc.), the way the data is accessed, modified, and organized shouldn't change. Generally, one should design DataManager and/or StateManager classes to handle this.
Also with GUIs, design your Components with OOP in mind. They should be modular, easily reusable, and extensible. If you are getting to the point where you are setting up a method to initialize and/or return a single GUI Component, then it is probably time to extend that Component and make it its own class.
These are just a few of the things I came up with off the top of my head.
|
While on DIC, I've seen a bunch of threads all asking basically the same thing- how can I get better at programming? The simple truth is that programming takes practice writing and debugging code. It is not something that comes overnight. So for those of you relatively new to (Java) programming, I've outlined a list of topics in a sequence from total novice to advanced programming, with focuses on various aspects of programming from data structures to Graphics to Networking.
Stage 1: You might fall into this category if you've never written a line of code before. Some things I would cover include: -Hello, World (print() vs. println(), \n escape sequence) -Primitive data types (byte, short, int, long, float, double, char, boolean) -Basic use of the String class and Primitive Wrappers for parse methods (ie., Integer.parseInt(String)) -User Input: JOptionPane vs. Scanner -If, Else-if, else statements; switch blocks, basic while, do-while, and for loops -Arrays and foreach loop
Stage 2: If you have completed all the Stage 1 topics with a decent proficiency or are in the AP Computer Science or comparable class, then you should work on these topics. Note that all of these topics are critical to sucessful programming in Java, so you should have a strong handle on them before going onto stage 3: -ArrayLists -Methods -Class design (constructors, instance variables and non-static methods, use of static) -Abstraction, Polymorphism (method overloading and overriding), and Inheritance -Interface design and usage -Object-Oriented Design Patterns -Working comfortably on a large project where most of the code is not yours.
Stage 3: If you have completed AP CS or Comparable Course and are proficient with all the above tools, then you may want to start on Stage 3 topics: -Data Structures and Collections (Linked Lists, Stacks, Queues, TreeMaps, HashMaps, TreeSets, HashSets, Graphs) -Advanced Generics (use of the wildcard operator and further parameterization; making your classes generic) -Graphical User Interfaces (Swing and AWT), as well as Graphics and Graphics2D classes for animations -Event-Driven Programming (possibly game programming) -File I/O -Database -Proficiency at maintaining code, including refactoring -Becoming comfortable with a domain-specific third party API. (i.e. something niche, not standard, and possibly poorly designed and a nightmare to work with) -Finding performance bottlenecks and designing solutions.
Stage 4: This is the advanced stuff, for which you should have a strong understanding of the previous 3 stages: -Networking, Client/Server design -Threading -Interacting with Websites and Webpages (ie., creating an RSS Feed Reader would fall into this category, while getting the webpage source might be more stage 3 topic) -Advanced Applications of Reflection -Drag and Drop with GUIs
I'd be happy to update this lis
...
Read more »
|
|
|
|