Java Returning a New Object *Complete Beginner - java

I am going to ask hopefully an easy question and I apologize in advance for any wording issues. I have a custom products class which works without an issue, within another class I create an array of products. see below:
products = new product[10];
product_count = 0;
I now wish to write a method to return not only the array of products but also the product_count, is it possible to return both as a new object? - if not could someone even show me how to return an object. I apologise if this seems a stupid question I am merely trying to learn, and thanks for any advice in advance
**thanks for all the responses - now I will throw a spanner in the works - I am trying to implement this method using java RMI - does anyone have an idea of how this would function?

You can use this to return your array:
public product[] returnArray(){
return products;
}
Keep in mind that you can just update your product_count instead of returning it.

Arrays know their own length. There's no need to return a length and the array separately. Just read the length field:
Product[] products = new Product[10];
System.out.println("The size of products is " + products.length);
Note that I capitalized the type name Product. Common convention in Java is for all class names to start with an uppercase letter.

Returning a single object can be done using return: return referenceName;
Returning multiple objects is easiest if you create your own class for it, or check for already existing implementations that might fit your use case. For example see: http://docs.oracle.com/javase/7/docs/api/java/util/AbstractMap.SimpleImmutableEntry.html

Related

Setting a Maximum limit for an ArrayList

So for school I am making a program where we are creating a booking system where people can book a ticket for a movie that has a capacity of 10 people. People are allowed to change the time of the booking to the next day as long as the theater is not full for that day.
An array will be no good in this situation as I need to be able to remove an object from the array and make another free space in said array, and then add the removed object to a different Array for the different day. This part is suitable for an ArrayList but it has no size limit so I'm stuck with what the best solution is. Any ideas that I can look into?
Thanks
You can try the below, start from an array and convert it to list via Arrays.asList. Just note you could only use the set() method on the List, and not the add/remove methods as these would modify its size :
String[] array = {"a1","b2","c3"};
List<String> fixed = Arrays.asList(array);
fixed.set(0, "new_string"); // OK
fixed.add("aNewString"); // This will throw an exception
You can extend a class which already has the functionality you need and only override the methods required to implement new functionality (i.e. enforce a size limit).
Consider the following solution:
public class CappedList<T extends Object> extends ArrayList<T> {
private final int maxSize;
public CappedList(int maxSize) {
this.maxSize = maxSize;
}
#Override
public boolean add(T e) {
if (this.size() == this.maxSize) {
//Already reached max size, abort adding
throw new IllegalStateException("List is maxed out");
} else {
return super.add(e);
}
}
}
For completeness, you need to also override all add and addAll overloaded methods. You can then use this CappedList class instead of a simple ArrayList. A utility function isMaxedOut would be handy, in order to avoid exception handling:
public boolean isMaxedOut() {
return this.size() == this.maxSize;
}
It all depends how far you are in understanding of the language.
Let's say, first of all as a base logic that you might consider is, that you should find what is unique for 10 tickets. Obviously it's a group, which has own unique identifier and that's a date, so you have to concentrate on binding your tickets to a date groups, then you should control the amount what you are populating per date, you might need advanced control logic, rather than an usual variable that might do the job for you.
First of all, I would not store tickets in a different variables per day.
Let's go into details.
If you are obsessed by using only one specific property and that's ArrayList, I found nice answer here
But to have more precise population and access to the list later, for example to filter out specific date and see those tickets that are sold that day you should do it with a bit more structured logic, rather than a simple ArrayList(), may be you should even use different Type of variable that you should store that data in.
If you are on a bit advanced programming course, from the brief observation, for a simple task I might say that there is the way to use getter and setter methods to implement limitations and you could use any type of object to store that data, beside ArrayList.
Or you could write own functions that can control adding and removing elements from a list.
Or in more advanced way, if you have been introduced to a class concept, you could use class to define a ticket and then you could construct any logic behind it. This last one is the best way to go - to write easily readable, understandable and reusable code, or store specific data and control it the way you want.

How do I access the data in Java objects returned by User.getAddresses() and User.getPhones()?

In com.google.api.services.admin.directory.model.User, many methods, such as getAddresses() and getPhones(), return a Java object that I can’t figure out what to do with.
Using toString(), I can see that the data I want is in the object (and looks like a list of HashMaps), but I can’t figure out how to convert it to a form that I can access, such as a list or array of UserAddress or UserPhone?
I’d also like to know how to build such objects so I can update users (although I suppose it’s likely that the answer to the first part of my question may make how to build them obvious)?
I have been able to update others things that don’t involve such objects, so I don’t need help with reading and updating in general, but I’ve struggling with these object for a couple of days now and can’t figure it out. Thanks.
The Google Directoy API uses JSON for communication. The Java client library used to communicate with the API parses and serializes the JSON to and from Java objects for easier usage in code. Have a look here for an idea of how it works: https://code.google.com/p/google-http-java-client/wiki/JSON
The problem with the current version of the library is that it doesn't serialize all the fields in the User class to usable objects. Instead maps, or list of maps, are used for complex fields. For example the phones field should be turned into a list of UserPhone objects, but instead becomes a list of maps. The only field that is being properly serialized is the name field, being a UserName object.
One way to manually turn the maps into the correct object is to use a json parser like Gson and parse the maps. Like this:
Gson gson = new GsonBuilder().create();
ArrayList phones = (ArrayList) user.getPhones();
for (Object phone : phones) {
UserPhone userPhone = gson.fromJson(phone.toString(), UserPhone.class);
System.out.println(userPhone.getType() + "=" + userPhone.getValue());
}
I believe those methods return a collection, in which case you'll probably want to access the items they contain via their iterator. Something like this should work:
ListIterator addresses = user.getAddresses().iterator();
while(addresses.hasNext()) {
Address address = addresses.next();
// do something with the address
}
If you're not familiar with the Iterator object, this article might help: How to use Iterator
Thank you, but User.getAddresses() and User.getPhones() do not have iterator methods, so neither of the answers proposed here will work.
"ListIterator addresses = user.getAddresses().iterator();" gets the compiler error “The method iterator() is undefined for the type Object”.
"for (UserAddress addr : user.getAddresses())" gets the compiler error “Can only iterate over an array or an instance of java.lang.Iterable”.
I finally found a way to get the job done, though. The follow codes actually works, even though it's difficult to believe this is the way I'm "supposed to" do it.
ArrayList<ArrayMap<String,String>> phones = (ArrayList<ArrayMap<String,String>>)user.getPhones();
for (ArrayMap<String,String> phone : phones)
System.out.println(phone.get("type") + "=" + phone.get("value"));
It’d be nice to get the data into an instance of UserPhone, but I can’t figure out how to do that (other than doing a get & UserPhone.setXxxx for every possible keyword).
I was able to update a phone number by passing User.setPhones() an ArrayList<UserPhone> that I built from scratch.

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.

Having trouble understanding how to create an array of linkedlists

Ok, so I have been reading every google result about creating an array of linkedlist, and most of the stack overflow threads, but I don't really understand what they are doing. Do I need to create a seperate class that extends linkedlist and then create an array of that class?
I have tried a million different ways of arranging this code, but this is what I have at the moment.
public static int[][] genPerms(int numElements, int totPerms) {
int permArray[][] = new int[totPerms][numElements];
LinkedList<Integer>[] elementsLeftList = new LinkedList<Integer>[numElements];
The error is generic array creation. Can someone explain to me what is actually going on here.
In addition to the solutions below I was told you can create an array of head pointers.
Thanks in advance.
It's not allowed to create generic arrays, do the following
#SuppressWarnings("unchecked")
LinkedList<Integer>[] elementsLeftList = new LinkedList[numElements];
it works OK
You can't currently create an array of generics in Java without going through a complicated process. Can you do the following instead?
List<LinkedList<Integer>> elementsLeftList = new ArrayList<LinkedList<Integer>>();
If you really need it as an array you can then get it from elementsLeftList.toArray() and cast the result.
You can read the following link for the explanation: http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ104

Adding all wrong answers into an array with Java - how?

I want to take all the questions that were answered incorrectly (it's a simple program asking math questions) and if they got the question wrong, add the question number to the array for further use.
But, I don't know how long this array will be, it could theoretically be of a different length each time the program is ran. So how would I set up the array?
You should use an ArrayList instead.
You could do something like:
ArrayList<String> wrongAnswers = new ArrayList<String>();
// Call this function with the user's answer as a parameter, when the answer
// has been determined to be incorrect.
public void wrongAnswer(String answer) {
wrongAnswers.add(answer);
}
public void printWrongAnswers() {
System.out.println("Wrong answers:");
for (String answer : wrongAnswers) {
System.out.println(answer);
}
}
Start with an ArrayList and then you can call toArray() to get an actual array.
You can also initialize an array whose size is the number of questions you have. Then keep a running count of missed questions, and simply trim the array at the end.
Look into using an ArrayList. This is an implementation of the List interface that is backed by an array.
Using the default constructor, it will start with a backing array of size 10 (but don't worry too much about this detail):
List<Question> questionList = new ArrayList<Question>();
You can then add elements:
questionList.add(question);
It will then resize this array as needed as you continue to add elements.
Since you probably know how many questions you are going to ask, you can stick to the array if you like and make it exactly as long as the number of questions you have. I would like to see the first person who succeeds in answering more questions incorrect then the number of questions available on the test
Use a collection, like a List implementation (like ArrayList), instead of an array. Then you can add by calling list.add(miss) and never worry about the size.
Do you specifically need an array? You can get the array, but in general, it's rare to specifically need one for requirements like these.

Categories