I don't know exactly how to word this, but I am wondering if it is possible to have "preferences" when choosing from a list.
For example, if I have a list of comparable tree objects with different variables (size, type, height), is it possible to "prefer" say bigger tree/ one type of tree over the other etc. In other words when choosing one object from the list, the tendency is to choose the largest tree or to choose one type of tree over the other, but not always (there is a stochastic element).
The idea you want is a sorted list. Various methods exist for this such as Collections.sort and Arrays.sort, as well as several java.util classes that automatically sort themselves (consider also some structures other than lists, like heaps). You can either make Trees Comparable<Tree> or make a Comparator<Tree> so that you can create lists arranged so that you can easily find the "most preferable" item (which will be moved to the front of the list) or the "least preferable" item (at the end of the list). See the documentation for the various classes I have mentioned for how to accomplish this.
Related
After going over different tutorials on Linked Lists I am seeing some mentioning the Java Node class for linking to the previous and next nodes and some not using it at all when creating a linkedList.
Is the Node class needed for Linked Lists ?
Why do some tutorials seem to create Linked Lists without it?
Also read that using the Node class is the "formal" way of creating a linkedlist
If you are asking whether (and why) you need to create Node instances to use a java.util.LinkedList, the answer is: No you don't. The list itself takes care of that.
(Note that the Node class that you linked to is not a linked list node. It actually denotes a node in an DOM. The actual Node class used internally by java.util.LinkedList is a private class.)
If you were asking why linked lists in general require a Node type, the answer is that they don't.
The other way of creating a linked list (that doesn't involve a Node type) is to directly chain the elements of a list to each other. This has a couple of consequences:
This requires the element class itself to have a next field (and possibly a prev field) for chaining the elements.
It means that a given element instance can only be a member of one list at a time, and can't be a member of the same list twice.
Together, these mean that the nodeless approach is incompatible with the standard java.util.List API.
The nodeless approach is also bad from the OO design perspective:
By the adding next and prev fields to the element type, you are breaking down abstraction boundaries and the separation of concerns.
The element instance now knows about the list that the element is part of.
The list abstraction only works for certain types of element, and has to take account of which list an element is a member of.
These things are liable to make the nodeless list abstraction harder to use ... and less reusable. (Though in limited circumstances, it may still be a good solution.)
You don’t technically necessarily need a node class, but the design with a node class is the good design. The design without one is the poor design.
This answer is slightly opinionated, but based on what we should all have learned in the first or at least the second year of programming, so consensus-based.
Say that we have a list of students. It’s now the natural responsibility of each Student object to have (“know”) the student’s contact information, courses enrolled in, grades taken, etc. It is not the natural responsibility of a Student object to know that it is part of a linked list, not to mention whether that list is singly or doubly linked. For this responsibility we have the Node class.
The design with the Node class has the further potential advantage that you can design and code a generic linked list and use it to instantiate a list of students, a list of teachers, a list of courses, etc. Stephen C in the other answer mentions further advantages.
Historical background: Where I learned data structures around 1980, we would fit each student record with a next pointer. (We learned singly linked lists. Doubly linked lists were only mentioned in passing.) What is nowadays considered the poor design. I had hoped that it had long gone out of use.
Performance (skip this paragraph until you really need it :-) : The poor design with next and previous references within the business objects like Student will typically perform slightly better. So if you are in a situation where performance is a Very Real Issue, you may consider it. It is no low-hanging fruit since it pollutes your design, so it will probably come near the bottom of your list of measures to take for better performance.
I'm working on an activity in which I have to determine what sort is used in a set of given methods, which I can't actually view as it's run from a .jar file which only contains .class files. All I can see is timing information (so I can determine what sort it could be based on time complexity). However, the elements being sorted are randomly generated integers, and duplicates are allowed. In order to properly identify the sorts, I'll have to somehow identify which methods are not sorting in a stable manner--without being able to view the source code or the array of integers. For example, I could have an array [1,2,3,9,5,64,8,5,1], which when sorted would be [1,1,2,3,5,8,9,64]. However, if something like a non-stable Selection Sort were used to sort this, the two 1 values would be switched in relative order to each other. How could I detect if something like this has occurred?
If you're constrained to using ints, there's no way you can test this as there is no way to distinguish two different 1s.
However, if you have the option of using Integers, and you specifically use new Integer() (rather than the autoboxing that comes with Java), you can compare the references in the original array with the new one.
As mentioned by Joe C, you would have to use some sort of wrapper class as there is no way to determine the difference between two primitive values. For example the Integer class could be used.
However there is a bigger issue here and it is an issue with logic. Just because a sorting algorithm is not guaranteed to be stable does not mean that given a particular input it will be unstable. Thus, measuring instability of an algorithm is ultimately an unreliable way of determining which algorithm is being used.
You could use instability as a way to narrow down your set of potential algorithms however to begin with I would recommend that you focus on the time it takes for different algorithms to process different kinds of inputs. Start with the obvious which is the time complexity of the algorithms: for example a bogosort will on average take much longer than a quicksort. Then delve into the inner workings of the algorithms that you are considering. Some algorithms with the same time complexities (eg: mergesort and heapsort) will both behave differently based on the type of input that you pass into them. For example one may be very slow to process a completely reversed input while another may do this very quickly.
If I have an ArrayList of custom objects which I need to be able to display them in various sortings (e.g. 4 types of sort so 4 comparators to use the proper member variables of the objects for the sorting) what is the most efficient way to do it?
I don’t think having e.g. 4 array lists of the objects sorted according to a specific comparator is optimal.
Is there another more efficient way than this?
Please note that I would need to have these objects sorted at the same time as they will be presented in the same page. So I can’t sort on demand
You could have different index arrays containing integers that are interpeted as indices of your original ArrayList. These can be sorted in different ways.
To access the list elements, use something like this:
list.get(index1.get(i));
I guess that FlyWeight design pattern could match your expectations.
Flyweight pattern is primarily used to reduce the number of objects created and to decrease memory footprint and increase performance. This type of design pattern comes under structural pattern as this pattern provides ways to decrease object count thus improving the object structure of application.
As you have your objects in an ArrayList, you can build up as many ArrayLists as different kinds of sorts you need for storing flyweight objects (basically id, order).
I came across an interesting piece of code while learning morphadorner manipulations. The code is below:
Collection<Object>[] nodes = someFunction()
My question is in what scenario is this declaration necessary and/or valid:
Collection<Object>[] nodes
I have seen:
Collection<Object[]> nodes
But cannot think of a scenario where I would need an Array of Collections. So again the question is, when would this be used?
This is the javadoc:
java.util.Set<java.lang.String>[]
findNames(java.lang.String text)
Returns names from text.
First of all,
Collection<Object[]> nodes;
and
Collection<Object>[] nodes;
are two different things. The first is a collection of arrays, whereas the second is an array of collections.
As to when you'd use the latter, my answer would be "rarely". While conceptually this is pretty simple, Java arrays and generics don't play together nicely.
It is therefore more common to see
ArrayList<Collection<Object>> nodes;
which is similar but much easier to deal with.
As to whether findNames() is an example of good design, my main objection is that it's completely impossible to guess from the function signature what the elements of the array are supposed to represent (or how many there are). For this reason, I would have done it differently, probably returning a custom class with two clearly-named accessors.
The code compiles, so it's probably valid Java.
It's necessary when the designer couldn't think of a better solution.
Which leaves us with: Is it good design?
Maybe but probably not. One scenario would be if the function always returns two or three collections (i.e. more than one but the number never changes).
You could create an object for this but since this is Java, this would take many, many, many lines of deadly boring code. It would also mean that you would have to come up with some useful names for each collection.
Taking the JavaDoc into account that you posted, it seems the number of arrays depends on the number of sentences in the text.
So in this scenario, I would return a List of Collections (since the order of sentences never changes and you might want to get them by index).
The designer might argue that you can add elements to a list but not to an array but I'd use an unmodifiable list.
So in this example, I'd say it's bad design.
Collection<Object>[] nodes
is Valid because it means that we are getting an array of Collection<Object> .
Whereas,
Collection<Object[]> nodes
means we are getting a Collection that contains arrays of Objects.
My question is in what scenario is this declaration necessary and/or
valid:
Consider the situation when you have different set of objects say (people). Each set belong to the people of particular country. And we create an array of set of specified size. In that case we use the following syntax:
Set<People>[] setOfPeople = new TreeSet<People>[5]; // We want to consider people of 5 different countries.
What is the most efficient way of maintaining a list that does not allow duplicates, but maintains insertion order and also allows the retrieval of the last inserted element in Java?
Try LinkedHashSet, which keeps the order of input.
Note that re-inserting an element would update its position in the input order, thus you might first try and check whether the element is already contained in the set.
Edit:
You could also try the Apache commons collections class ListOrderedSet which according to the JavaDoc (if I didn't missread anything again :) ) would decorate a set in order to keep insertion order and provides a get(index) method.
Thus, it seems you can get what you want by using new ListOrderedSet(new HashSet());
Unfortunately this class doesn't provide a generic parameter, but it might get you started.
Edit 2:
Here's a project that seems to represent commons collections with generics, i.e. it has a ListOrderedSet<E> and thus you could for example call new ListOrderedSet<String>(new HashSet<String>());
I don't think there's anything in the JDK which does this.
However, LinkedHashMap, which is used as the basis for LinkedHashSet, comes close: it maintains a circular doubly-linked list of the entries in the map. It only tracks the head of the list not the tail, but because the list is circular, header.before is the tail (the most recently inserted element).
You could therefore implement what you need on top of this. LinkedHashMap has not been designed for extension, so this is somewhat awkward. You could copy the code into your own class and add a suitable last() method (be aware of licensing issues here), or you could extend the existing class, and add a method which uses reflection to get at the private header and before fields.
That would get you a Map, rather than a Set. However, HashSet is already a wrapper which makes a Map look like a Set. Again, it is not designed for general extension, but you could write a subclass whose constructor calls the super constructor, then uses more reflection to replace the superclass's value of map with an instance of your new map. From there on, the class should do exactly what you want.
As an aside, the library classes here were all written by Josh Bloch and Neal Gafter. Those guys are two of the giants of Java. And yet the code in there is largely horrible. Never meet your heroes.
Just use a TreeSet.