how can I create an array of tuples in jsp (java)
like
(a:1, b:2)
(c:3, d:4)
...
...
Create a tuple class, something like:
class Tuple {
private Object[] data;
public Tuple (Object.. members) { this.data = members; }
public void get(int index) { return data[index]; }
public int getSize() { ... }
}
Then just create an array of Tuple instances.
if you want an arbitrary size tuple, perl hash style, use a Map<K,V> (if you have a fixed type of keys values - your example looks like Map<Character,Integer> would work - otherwise use the raw type). Look up the java collections for more details about the various implementations.
Given those tuples, if you want to stick them in an sequential collection, I'd use a List (again, look up the collections library).
So you end up with
List<Map<K,V>> listOfTuples
if you need something more specific (like, you'll always have x1, x2, x3 in your tuple) consider making the maps be EnumMaps - you can restrict what keys you have, and if you specify a default (or some other constraint during creation) guarantee that something will come out.
There's no default pair / n-tuple class in Java; you'd have to roll your own.
you could use the HashSet class.
If you are dealing with tuples of fixed size, with fixed names of the attributes, define a simple data class of your own, and then define the array of this class.
If on the other hand you want the attribute names to be flexible and determined at runtime, use a Map structure. In your example above, it seems like HashMap<String,Integer> can do the job. You may want to wrap it in order to reduce its functionality, and maybe also add more specific functionality.
I know I am late to the party but an array of points should do the job.
Check here to see the documentation about points.
Related
I am developing an application where as a background I need to monitor the user activity on particular objects and later when they are visualized they need to be sorted based on the order of which the user used them ( the last used object must be visualized on the first row of a grid for example.)
So if I have an ArrayList where I store the objects which the user is dealing with in order to add the last used object I need to check if it is already in the list and then move it at the first position. If the object is not there I simply add it at the first position of the list.
So instead of doing all these steps I want to make my own list where the logic explained above will be available.
My question is which scenario is better:
Implement the list interface
Extend the ArrayList class and override the ADD method
Create a class that contains an ArrayList and handles any additional functionality.
I.e. prefer composition over inheritance (and in this case, implementing an interface). It's also possible to have that class implement List for relevant cases and just direct the (relevant) operations to the ArrayList inside.
Also note that LinkedHashMap supports insertion order (default) and access order for iteration, if you don't need a List (or if you can suitably replace it with a Map).
So instead of doing all these steps i want to make my own list where
the logic explained above will be available.
I would try to refactor your design parameters (if you can) in order to be able to use the existing Java Collection Framework classes (perhaps a linked collection type). As a part of the Collections Framework, these have been optimized and maintained for years (so efficiency is likely already nearly optimal), and you won't have to worry about maintaining it yourself.
Of the two options you give, it is possible that neither is the easiest or best.
It doesn't sound like you'll be able to extend AbstractList (as a way of implementing List) so you'll have a lot of wheel reinvention to do.
The ArrayList class is not final, but not expressly designed and documented for inheritance. This can result in some code fragility as inheritance breaks encapsulation (discussed in Effective Java, 2nd Ed. by J. Bloch). This solution may not be the best way to go.
Of the options, if you can't refactor your design to allow use of the Collection classes directly, then write a class that encapsulates a List (or other Collection) as an instance field and add instrumentation to it. Favor composition over inheritance. In this way, your solution will be more robust and easier to maintain than a solution based on inheritance.
I think LinkedHashMap already does what you need - it keeps the elements in the order they were inserted or last accessed (this is determined by the parameter accessOrder in one of the constructors).
https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html
EDIT
I don't have enough reputation to comment, so I'm putting it here: You don't actually need a map, so Venkatesh's LinkedHashSet suggestion is better.
You can do something like this:
<T> void update(Set<T> set, T value) {
set.remove(value);
set.add(value);
}
and then
LinkedHashSet<String> set = new LinkedHashSet<>();
update(set, "a");
update(set, "b");
update(set, "c");
update(set, "a");
Iterator<String> it = new LinkedList<String>(set).descendingIterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Output:
a
c
b
You might try using HashMap<Integer, TrackedObject> where TrackedObject is the class of the Object you're keep track of.
When your user uses an object, do
void trackObject(TrackedObject object)
{
int x = hashMap.size();
hashMap.add(Integer.valueOf(x), object);
}
then when you want to read out the tracked objects in order of use:
TrackedObject[] getOrderedArray()
{
TrackedObject[] array = new TrackedObject[hashMap.size()];
for(int i = 0; i < hashMap.size(); i++)
{
array[i] = hashMap.get(Integer.valueOf(i));
}
return array;
}
A LinkedHashSet Also can be helpful in your case. You can keep on adding elements to it, it will keep them in insertion order and also will maintain only unique values.
Probably some basic stuff I am missing here, but what is the best way to select objects matching some criteria from list?
Say we have:
class MyObject {
int id;
String type;
// getters..setters
}
I use it:
List<MyObject> myObjects = new ArrayList<MyObject>();
myObjects = getListOfObjects();
Now lets say that in the myObjects there are 10 items and 3 of them have type=="bla". At the moment I am just looping thru all the objects and within the loop decide if I want it or not, but is there a better way?
I remember that in C# I used to have something like
myObjects.Where(x => x.type.equals("bla"));
PS, I am targeting Java 7 so no lambda for me yet.
I don't think you can do this without creating an index of some kind. So e.g. having Map<String, Map<String, Set<MyObject>>> you could then call index.get("type").get("bla"). But you would have to first construct this structure. This would be useful if a) there are no changes to the properties AND b) you have a LOT of objects. For 10 objects the performance is of no concern here and I would simply just do what you're doing right now and hide it inside some nice handy method.
You could use the LambdaJ library and its Lambda.exists method with some custom Hamcrest matcher. Then you could make your main code look like this:
if (exists(myObjects, typeIs("bla"))) { /* ... */ }
...provided that you create that custom matcher method typeIs by yourself. But I wouldn't go down this way if I had just one place with just 10 items in a list.
It also depends on your data: if your list is sorted, you could do a binary search on it. That's more useful if you have thousands of items in the list, though.
Finally, you could just use Collection.contains: myObjects.contains(blaElement), but that requires that the blaElement has such an equals method that returns "true" when the type matches.
I would like to reference an array with an enum type. This is a pretty standard thing in C++ (my origin), however I'm unsure if this is possible/desirable in Java.
For example, I would like to have an enum such as:
public enum Resource {
COAL,
IRON
}
Then later I would like to reference like this:
Amount[COAL] // The amount of coal
Price[IRON] // The price of iron
I don't want to make Amount and Price fields of Resource as I would like a list of objects (orders for resources) grouped by the resource type. Manually assigning an int to each type of Resource is no better than public static int final BLAH I feel, nothing gained.
In essence, I'm looking for the enum of C++ which tags things. I realise that this could be the 'wrong' way of doing things in Java, so feel free to point me in the direction of the correct Java ethos.
In C++, an enum is effectively an alias for an integer. In Java, they're "proper" objects - which is why you can't use them as an array reference.
If you want to look up the value in your array that's associated with a particular enum object - that sounds like a Map to me! How about replacing those arrays with an EnumMap<Resource, Double>?
The EnumMap class is optimised for use with enum keys, such that it does end up using an array keyed on the enums' ordinal (integer) value behind the scenes. So it's much faster than a general-purpose hashmap, and you get the speed of an array-based solution with the semantic expressiveness of a Map - it's the best of both worlds.
You can do almost it. In contrast to C++ where enum is just an int, Java's enum is class. So you can't use it as an index of array. But every enum element has ordinal() that is int, so you can say
amount[COAL.ordinal()]
price[IRON.ordinal()]
But you have a better approach. Can add methods to enum, so it will look like:
IRON.price(amounts)
COAL.amount(prices)
I think this approach is much better.
Each Java enum element has an ordinal associated with it, indexed from zero based on the order of definition in the enum. Just use e.g.
COAL.ordinal()
However, it sounds to me like you'd be better off creating a class e.g. Order with fields for Amount and Price and then keeping a collection of those e.g. in a Map indexed by the enum elements.
e.g.
Map<Resource, Order> orders = new HashMap<Resource, Order>();
orders.put(Resource.COAL, new Order(price, amount));
I think you're looking for EnumMap, http://docs.oracle.com/javase/1.5.0/docs/api/java/util/EnumMap.html
It's not exactly an array, but because the key is an enum, it's still space efficient.
It ends up like:
amount.get(Resource.COAL)
Maps are very good for more dynamic data. But you also have to code all the checking for double names, double values, existing names/values and all the stuff. And even in this case if you do the error, it will be found at runtime only.
For more static data better use not primitive enums, but new type enums from Java 6. They are excellent! And errors will be found by compiler.
public enum Resource{
COAL(0), IRON(1);
int index;
private Resource(int index){
this.index=index;
}
}
...
amount[Resource.COAL.index]=...
But better variant is:
public enum Resource{
COAL(538,0.5f), IRON(115,1.5f);
int amount;
float price;
private Resource(int amount, float price ){
this.amount=amount;
this.price=price;
}
}
...
Resource.COAL.amount=...
You can use their name.
You could make the cycle through all enum:
for(Resource resourceType: Resource.values()) {
String toOutput=resourceType.name()+" amount="+ resourceType.amount;
}
Unfortunately, you'll need a slightly longer syntax:
Amount[COAL.ordinal()] // The amount of coal
Price[IRON.ordinal()] // The price of iron
If that is not to your liking, constants may be your only option, i.e.
public class Resource {
public static final int COAL = 0;
public static final int IRON = 1;
}
Hope that helps.
This question already has answers here:
How to return multiple values? [duplicate]
(3 answers)
Closed 3 years ago.
This is a small issue, as I could easily whip up a pair class to do the job. I don't really want to do this though, and I feel like there should be some simple, built-in, java-like way of returning two values. What do you guys is the best, simplest way of doing this? Arrays? Some other data structure?
As far as I know, there is unfortunately no built-in representation of a pair in Java (and I certainly wish there was). Personally, when I code a project where I find that a pair class often would be useful, I create a generic Pair<T, U> class (which is probably what you were thinking of). Returning an array is a fast and simple way, but you might come to regret it later, because people who use your method will wonder whether the method might at some point return more than two values.
Whichever solution you choose: whenever you feel that you need a Pair, you should consider whether the time saved today by using e.g. a generic Pair class really is worth the loss of information to the next person who reads the code (and that person may well be you in six months). Writing a separate class for the return type takes more time now, but it would convey more information to those that use your method (namely, it tells the users what the return value represents, and contains useful member names for the two values). If it is a non-public method that is used only a few places, though, a Pair is more acceptable.
Using a container class is the easiest way.
public class Pair<T, U> {
public final T t;
public final U u;
public Pair(T t, U u) {
this.t= t;
this.u= u;
}
}
The closest thing I've seen to a "pair" in the standard libraries are the Map.Entry interface and the AbstractMap.SimpleEntry and AbstractMap.SimpleImmutableEntry classes that implement it.
If both objects are the same class an array is easier to use.
Apache Commons Lang3 provides an abstract Pair class with a couple implementations including ImmutablePair and MutablePair.
Three approaches, all not so great:
Roll your own Pair<A, B>. You said you didn't want to do that.
Return a Object[]. This is not type safe.
Mimic out variables or pointers by supplying single element arrays as parameters.
An example of #3:
public boolean getUserDetails(String userId, String[] lastName, String[] firstName, Date[] dob) {
assert lastName != null && lastName.length == 1;
assert firstName != null && firstName.length == 1;
assert dob != null && dob.length == 1;
...
}
The third option makes life painful for the caller.
So like I said, no nice solution.
As an aside, Scala uses various Tuple classes (up to 21-tuple, from what I remember) to help you with this.
There is a pair class in JavaFX, but you shouldn't use it. What you SHOULD use is something like this:
// We've skipped imports and package declarations
public final class YourClass {
/* Assume there is a bunch of stuff here */
// I don't know what method you're using, so forgive the silly example
public YourClass.Pair sillyExampleOfPairs(String someString) {
return new YourClass.Pair(someString, someString.length() * 13);
}
#Value // Lombok annotation.
public static class Pair {
String text;
int integer;
}
// this is an even more succinct possibility
#Value public static final class ShorterPair {String text; int integer}
}
While the name Pair here is obviously not that well chosen, and you should choose a more descriptive name, the obvious ways this will work (the fields are final private and you have a getter on each, because of the annotation), should not be lost on you. And while yes, this is slightly more wordy than using Pair, it's much more robust. What if you do need to add an extra parameter to the return value? You "only" need to change this class then. And you can update all the relevant JavaDocs immediately, which is also nice. If you have to change types, they would both entail similar amounts of work.
As long as you're only adding stuff, the old getText() and getInteger() methods would keep working as they did before. You also avoid having to add Yet Another Dependency to your projects. It's not a big win. Having Pair available is nice for prototyping, but it's not nice for later.
My final theoretical CS-y argument is that Pair is the same type as Pair. But if you have a Phonebook.Entry (with String and int) and say, Inventory.Item (with a name and a number of items we currently have inventoried), these two are very distinct types, which do very distinct things. You can't put one into the other. This is a Good Thing.
It's also much clearer for us poor bastards that have to go and debug your systems to see something like "com.name.project.something.something.Phonebook.Entry" in a stack trace than "org.apache.commons.lang3.tuple.Pair". One of these tells me WHAT I'm supposed to be looking at, and gives me some info on WHY I'm seeing a pair. The other says... nothing.
Now you might not care that you have to type for 3 extra seconds to save me 3 minutes. But I choose to believe in the goodness of your heart, and the nobility of your soul. Therefore, do the right thing.
Write a small static class instead.
I have been told by experts that when faced with the question of pairs, one of two things is true:
You need to rethink your structure (this blunt answer doesn't help anyone)
You need to build your own class to hold the pair
I would suggest that the second case is not all that abnormal. However, if what you are doing seems too trivial for introducing a new class, then using a Map could work, as others have suggested. If you are simply sending a single response back, then a Map seems like a bit much.
If a list of pairs sounds like it would work, and you need to maintain order, you could try a LinkedHashMap so that order is maintained.
if both are integers then I would advise a java.awt.Point but otherwise just create a container class with two objects x and y
Some observation of mine:
Array is bulit-in, fast and easy to use, although imposible to expand its capacity. What if you want 3 values to be returned after 3 months?
ArrayList/other colletions can be good, allows you to increment the capacity(initially 10).
Note that Vector can be overkill in comparison to ArrayList when you only want to store 2 values to be fetched later. Map also can be good because it's always sorted and ordered.
Some user-defined class: maybe an option if is meaningful(means that the data returned is important-ish to be a Java Bean), and you want to store more than just 2 integers into it. Readibility is better in case you add more notes in its Javadoc. Can be expanded as you like, just add fields in this class. Slower, but safer.
I have to refactor an existing project, which is not that small. It contains a lot of arrays declarations and accesses:
(X is not a generic type, it's just a placeholder).
declarations: X[] and X[][],
access: someArray[i] and someArray[i][j].
I have to rewrite everything to use generic Lists:
declaration: List<X> and List<List<X>>,
access: someList.get(i) and someList.get(i).get(j).
I couldn't find a possibility to automatize such refactoring, neither in Eclipse, nor in Netbeans (both newest versions).
Are there some tools available to do such refactoring?
EDIT:
The project is very algorithm-oriented. Internal implementation of algorithms will not be touched. But the exposure to the external world must be changed. Most classes are made in such a way, that they only hold some result arrays or arrays of arrays.
exposure to the external world must be changed
In that case I'd avise not to change it everywhere, but to :
change only return types of the public methods
write an utility method, which looks like:
public static List<List<X>> asList(X[][] x) {
List<X[]> list = Arrays.asList(x);
List<List<X>> newList = new ArrayList<List<X>>(list.size());
for (X[] xArray : list) {
newList.add(Arrays.asList(xArray));
}
return list;
}
use that method to change the only result of each public method. I.e.
public List<List<X>> someAlgorithm(...) {
// algorithm code
X[][] result = ...;
return Utils.asList(result); // add only this line
}
I can hardly agree that things you are going to do could be called 'refactoring'.
Arrays has some possibilities that lists don't have (and of course vise versa).
For example, if you create new array of 10 integer elements then its size is 10, and it has ten zero values.
You can also use its index in some tricky way. For example, think about radix sort algorithm. To implement it with lists you should first add a lot of zeros to this list and you'll get twice worse performance.
I'm telling this to explain the idea that it's almost impossible to implement robust tool for doing what you want to do.