code factory method - java

I want to create something I can only describe as a "code factory method".
To avoid code repetition, I want to create a method which contains the code to be executed, but with "placeholders" where the types are supposed to go. The method would of course take these types as parameters and place each one in its appropriate spot. For example:
void factory(placeholder1, placeholder2){
ArrayList<placeholder1> List = new ArrayList<placeholder1>;
Placeholder2 variable;
}
factory(String, Integer);
would yield:
ArrayList<String> List = new ArrayList<String>;
Integer variable;
any ideas how I would go about this?
Your help is much appreciated.
EDIT: Thank you for all the feedback. I was going with the generic approach and it was working for awhile until I came across what I believe someone mentioned earlier. I want to use one of the methods within one of the generic objects like:
Integer variable = new Integer();
variable.isInteger();
It doesn't appear that I will be able to do this using generics. Is there possibly a workaround to this?

Rather than simply adopting generics, it looks like you want some sort of macro facility. Java doesn't have that. For example, to expand your example a bit, you couldn't do anything like this:
factory(String, Integer);
List.get(variable);

Here's how it would look:
<placeholder1, placeholder2> void factory(){
ArrayList<placeholder1> List = new ArrayList<placeholder1>;
placeholder2 variable;
}
this.<String, Integer> factory();
But I agree with matt that you should read up on generics. Also, be cautious of type-erasure as this might not do everything you expect.

Related

What kind of List is List<Object> list = Database.getAllData();?

I have the following question:
if I have the following line of code:
List<Position> allPos = posDBM.getAllPos();
Position is an object
posDBM is a SQLite Database Manager class, which manages the SQLite database,
getAllPos() returns all database data.
The return type of getAllPos() is List<Position>.
If I want to initialize a List<> like this List<Position> pos = new, I have to specify the type of the List (ArrayList, LinkedList, etc.) .
So back to my question, what kind of List do I have, after I filled the list from the database?
I would guess it's an ArrayList , but I can't find any source to back this up. It's just a matter of interest...
You don't have to know; that's the point. The interface is what matters to you, not the implementation.
You can't know without looking at the source of that method. But even if you do, it's immaterial to your client. All you call are List methods.
That you will find in getAllPos() source code. List<Position> due to Polymorphism will accept all classes implementing List interface.
It you are just curious, then one way to find out is to do something like this:
List<Position> allPos = posDBM.getAllPos();
System.out.println("The class is " + allPos.getClass().getName());
Of course, you don't need to know ... because you don't need to instantiate the list implementation class yourself. The database management code deals with that.
The returned List<Position> is a generic or a Strongly Typed list. The option that you were asking is about ArrayList which specifies a list that can take up any object. This will require an overhead of Boxing and Unboxing when writing / reading using the ArrayList.
Ideally you should not worried about the actual implementation , once you have List returned from the method call , you can just iterate over it like this .
List<Position> allPos = posDBM.getAllPos();
for(Position position : allPos){
//Your code goes here
}
And if you want to initialize a new list you can do it in many ways by using different implementations of List interface , now which implementation you want to choose very much depends on your requirement.
I would suggest you to add a breakpoint and see allPos variable after posDBM.getAllPos(), the debugger should tell you the Type.

Java - Indexing an Interface?

This is probably a really stupid question, so please forgive me. But this morning, I've come across a piece of Java syntax that I am completely unfamiliar with. The syntax is as follows:
public MyInterface[] getThings() {
return new MyInterface[0];
}
Obviously, I've changed the name of the interface, and of the method, but otherwise this code sample is unchanged.
I'm confused by this syntax, as it seems to be indexing an interface/class (not even an object)?! Also, the use of the new keyword, to instantiate an interface?!
I've genuinely attempted to Google this, in order to find an answer. But as it's syntax that I'm unfamiliar with, in addition to using the line of code itself as a search term, I've just been guessing at what terminology to use. And unfortunately, I've failed to find anything that explains this syntax for me. Hence, I'm hoping that someone on Stack Overflow might be kind enough to help me to understand this.
It's just creating an empty array. No instances of the interface are being created. It's equivalent to:
return new MyInterface[] { };
Or:
MyInterface[] array = {};
return array;
Specifically, it's an ArrayCreationExpression, as seen in section 15.10 of the JLS.
The function returns an empty array supposed to holding objects of type MyInterface.
It's similar as if you would use String[] to return an array of strings.
it just returns an empty array of MyInterface (size is 0). an array is an array, no matter, of which type the array is. it can be a primitive datatype, a class or an interface, too.

Declaring a LinkedList in Java

I always learn when we declare a collection we should do, Interface ob = new Class(), if i want to use for example a LinkedList i'll do List ob = new LinkedList(), but then i can't have access to all methods from LinkedList.. Isn't LinkedList ob = new LinkedList() 100% correct?
Isn't LinkedList ob = new LinkedList() 100% correct?
Well I'd suggest using the generic form, but sure - if you want to use functionality which is specific to LinkedList, you need to declare the variable accordingly.
You might want to check whether the Deque<E> or Queue<E> interfaces have what you want though. If they do, use those in-keeping with the idea of describing what you need rather than what implementation you'll use.
Yes,
LinkedList<...> items = new LinkedList<...>();
is perfectly correct if you know that items will depend on methods of LinkedList<T> that are not captured in the List<T> interface.
You should always try to keep the declaration at the highest level possible, meaning that you should stop at the highest level that provides all the functionality that you need: if List methods are not enough, you're perfectly fine with your LinkedList declaration.
If you actually have a need to use methods that are not on the List interface, there is certainly nothing wrong with using LinkedList's API. The general rule of programming to the List interface recognizes that 1) it's pretty rare to need those methods, and 2) in most people's experience, it's way more likely that I discover I need to sort the list and/or use a lot of random access, and decide to switch to an ArrayList, than it is I need one of the methods only LinkedList has.
It may be also that you could be programming to the Queue interface, if you find List isn't giving you what you need.
The rule "always code to interfaces" must be taken with some flexibility. What you are suggesting is fine, and as you came to the conclusion, the only option.
As a side note, coding to concrete classes like this is faster is most JVMs. Deciding whether the performance is worth breaking the rule is the hard thing to decide.
LinkedList is a generic. You should be doing:
LinkedList<String> linkedList = new LinkedList<String>();
(or whatever else you need to store in there instead of String)
Not exactly 100% correct.
A preferred way to declare any collection is to include the data type it's holding. So, for your example, it'd be LinkedList<Integer> ob = new LinkedList<Integer>();.
Nope.. This would be wrong, at the later stages if he wants to change his implementation from linked list to any other implementation of list type he will go wrong... So better to use the interface level declaration.
I won't always suggest you to use generics .....
Coz sometimes you may need to wrap different objects as here....
String str="a string";
boolean status=false;
LinkedList ll = new LinkedList();
ll.add(str);
ll.add(status);
In some situations like case of RMI, u can only send serialized data.....and suppose you want to send a class object(which is unserialized).......There you can wrap the members of the class(primitives) in a LinkedList and pass that object as a whole.......not worrying about the huge number of arguments......
Consider for eg:
public Class DataHouse
{
public int a;
public String str;
.
.
.
}
Now Somewhere u need to pass the objects....
You can do the following....
DataHouse dh =new DataHouse();
LinkedList ll = new LinkedList();
ll.add(dh.a);
ll.add(dh.str);
// Now the content is serialized and can pass it as a capsuled data......
you can still have access to LinkedList methods by using List, all you have to do is to type cast
for example
((LinkedList)ob).add()
The point of using generic List and not LinkedList is because in case you simply change the type of lists you are using (let's say double linked list) your program will still work Generics are to simplify your code to be more portable and more "changeable"
Actually it would be better if it would be parametrized as both are raw types.

Java: How to initialize a List of Typed Objects?

So I've been searching a while for the answer to this and I'm just not sure how it works.
I'm trying to make a list of BloomFilter<String> objects.
The class definition for the BloomFilter is:
public class BloomFilter<E> implements Serializable { ...
The <E> allows the user to pick what type of elements are going into the filter. In my case, I need strings.
Somewhere else in the program, I need 4 BloomFilter<String> objects.
My question is: How do I initialize the following line?
private static BloomFilter<String> threadedEncrpytionFilters[] = null;
threadedEncryptionFilters = ???
This seems similar to creating a list of ArrayLists? Is that also possible?
After seeing that someone alread answered this question I wanted to remove this answer but I see by the comments that people are still confused so here it goes :)
The specification clearly states, that what you want to do is illegal. Meaning:
BloomFilter<String> threadedEncrpytionFilters[] = new BloomFilter<String>[4];
won't compile. You can't create an array of concrete generic classes. When it comes to generics you can store in arrays only:
raw types
unbounded wildcard parameteriezd types
The workaround to your problem is, as already stated, to change the array to a List<BloomFiler<String>>.
This behaviour is actually pretty logical if you take into account how Java handles generic types at different stages (compile, runtime etc). After understanding that you'll see that arrays of concrete generic types wouldn't be type-safe. Here's a mighty good read on this subject: http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ104
List<BloomFilter<String>> list = new ArrayList<BloomFilter<String>>();
list.add(new BloomFilter<String>());
list.add(new BloomFilter<String>());
list.add(new BloomFilter<String>());
// ... and so on
Consider this:
private static List<BloomFilter<String>> threadedEncrpytionFilters =
new ArrayList<BloomFilter<String>>();

How to create new variable in java dynamically

Is it possible to create new variables in java dynamically.
class A {
methodA(String variableName) {
}
}
So if new method is called twice, 2 new variables should be newly added to this class?
Is it possible?
No. Have you considered storing a Map<String, Object> in the class instead? The keys in the map would be the "variable names" and the values in the map would be the logical variable names.
If you could give more information about what you're trying to achieve (from a high-level perspective) that would help.
No, this is not possible to do in Java.
The fields in a class is determined at compile time and can't be changed during runtime (except though sophisticated techniques such as class reloading though for instance JRebel). I would however not recommend doing this, unless you're writing some IDE for instance.
A class and its members are defined and then compiled to bytecode, so they cannot be readily modified at run-time. That said, there are a number of libraries out there, such as cglib, which provide runtime modification functionality. This page can tell you more: http://java-source.net/open-source/bytecode-libraries
(This is not to say that runtime modification is the right thing to do!)
In a good design, a class must represent something, semantically speaking. You design it to represent an object in your system.
If you want to add more things to a design in run-time, well, something's not quite right -- unless, of course, the design needs adding information in run-time, and there are tons of data structures just ready for the job!
Check out Maps in Java, for example.
Following is the way that i have implemented and helped me to fix my solution easily without much hurdles.
// Creating the array List
List accountList = new ArrayList();
for(int k=0;k < counter;k++){
accountList.add(k, (String)flowCtx.getValueAt("transitId"+m));
}
Iterating the loop and adding the objects into the arraylist with the index.
//Retrieving the object at run time with the help of the index
String a = accountList.get(i));
Using a HashMap could be a solution. For example, if we have the following class:
class Staff {
private HashMap<String, Object> mylist = new HashMap<String, Object>() ;
void setNewVar(String s, Object o) {
mylist .put(s, o);
}
HashMap<String, Object> getVar() {
return mylist;
}
}
I can use it as:
staff.setNewVar("NumVars",11);
staff.setNewVar("NumBatches",300);
...
and then:
staff.getVar()
wherever you need. I use it to convert some variables (the number can change) to JSON, successfully.

Categories