I am iterating through an array of objects (different website types). But I want to be able to show which website has the highest amount of members. Initially my code shows the amount of members of each website, but my code isn't complete as im not sure how to compare the objects to see which has the highest amount of members. Current code:
public static void mostUsers(){
for (Website w: websiteTypes){
// check if the array index is not null
if (w!=null){
System.out.println(w.getType() + "has:" + w.getMembers());
System.out.println(); // line break
**//Code to compare amount of users on each site and display highest**
} else {
// no more records so quit loop
break;
}
}
}
You need to keep track of the maximum number of users while your iterating.
Initialize a variable called maxWebsite to null before your loop
Initialize an integer called max to Integer.MIN_VALUE before your loop
While your iterating, test if w.getMaxUsers() is superior than the max value.
If it is, update accordingly the maxWebsite and max variables
Note : remove the else statement in your loop, you have to iterate all the elements of your array.
If you're using Collections, that could be simple using Collections.max with a custom comparator :
List<Website> l = .......
l.removeAll(Collections.singleton(null)); //remove null elements from the list
Website maxWebsite = Collections.max(l, new Comparator<Website>(){
#Override
public int compare(Website arg0, Website arg1) {
return Integer.compare(arg0.getMaxUsers(), arg1.getMaxUsers());
}
});
Use a Comparator, or have Website extend Comparable.
Then, sort your collection of Websites using sort. The websites with the most views will then be at the beginning of your collection.
Related
I have an array list in a class the array is called realtorList. From my main class I store objects with realtor data to the realtorList.
My data that is stored to a text file and is read in the first line.
This is the first element in the realtorList after I store the first line of data.
[Realtor{licenseNumber=AA1111111, firstName=Anna, lastName=Astrid, phoneNumber=111-111-1111,
commission=0.011}]
When I read the next line of data from the input file I need to see if the licenseNumber in bold already exists in the realtorList. I am having trouble figuring out how to go about doing this.
For example if the next realtor data license number is AA1111111 how do I check the realtorList for AA1111111 which does exist for this example.
A really simple way to do this would be to have a String ArrayList running alongside (for example, one called licenses) and use an if statement with indexOf to return if that license value is already in the List. Since the licenses ArrayList only has one value it can be easily searched with indexOf.
An example would be
private boolean checkLicense (String licenseNumber) {
int i = licenses.indexOf(licenseNumber);
if(i == -1) {
return false;
} else {
return true;
}
}
Similar code works in one of my projects where a dynamic List of motors for a robot checks to see if there's already a motor with the listed port before adding a new one.
Another method could use a for loop for a linear search such as
private boolean checkLicense (String licenseNumber) {
for(int i = 0; i < (realtorList.size() - 1); i++) {
if (licenseNumber.equals(realtorList[i].getLicenseNumber())) {
return true;
}
}
return false;
}
This would perform a linear search of each and every object until it finds it (it would need to be in a method like the one for the example above to work this way)
I have a class Section with several methods including methods get_key() and get_angle(). Items of type Section are added to a hashtable implemented in class Hashtable.
According to my task I should delete such elements from the hashtable which have bigger value of function get_angle() than given_value.
class Hashtable{
private Section[] hash_array; //array of cells of the hashtable
public int size;
public void remove_given(double given_value)
{
for(int i = 0; i < size; i++)
{
if (hash_array[i] != null)
{
double value = hash_array[i].get_angle(); //value of needed function to compare
if (value > given_value)
{
int key_ = hash_array[i].get_key(); //get key for the item in order to delete it
Delete(key_); //delete item
}
}
}
}
}
But the method doesn`t delete any elements. I checked the method Delete() separately and it works just fine as well as other methods called on this method . I really need to figure it out. So I will be grateful for your help.
Debug your code, does it enter the for-loop. How do you initialize the value of size variable? If you forget to initialize it by default it will be zero. It is better to get the size from the hash_array.length.
For one thing you're using the uninitialized global var, size, the size used in the for loop needs to be the size of the Hash collection. Also how is the Hash initialized? Does it contain what you think? I'd follow the aforementioned suggestion to step through the code with a debugger, perhaps the keys aren't what you think they are...
My Problem
I have a fixed-size ArrayList which contains custom variables. Despite of the ArrayList having a fixed size, sometimes a lot of them will actually be null. The thing is that I need to return the ArrayList without the null variables inside it. One important thing to note: the ArrayList will have all of its non-null items first, and then all of the nulls below them, e.g., the elements are not mixed. Example: [non-null, non-null, .... null, null, null]
My workaround
I though of creating a for-loop that checked (from last to first index) each of the elements inside the ArrayList to determine if it's null or not. If is null, then I'd call this code:
for (i = size-1; i >=0 ; i--) {
groupList = new ArrayList<>(groupList.subList(0, i));
}
My question
If the ArrayList is too big, this method might me particularly slow (or not?). I was wondering if there exists a better, more performance-friendly solution. AFAIK the .subList method is expensive.
You can have a variant of binary search, where your custom comparator is:
Both elements are null/not null? They are equal
Only one element is null? The none null is "smaller".
You are looking for the first null element.
This will take O(logn) time, where n is the size of the array.
However, taking the sublist of the ArrayList that is none null (assuming you are going to copy it to a new list object), is going to be linear time of the elements copied, since you must "touch" each of them.
This gives you total time complexity of O(logn + k), where k is number of non null elements, and n is the size of the array.
Following all of your outstanding advices, I modified the original method so that I can take the last (first) ever null item position and call the .subList method just once. And here it is:
int lastNullIndex = size - 1;
for (i = lastNullIndex; i >= 0; i--) {
if (null == groupList.get(i)) {
lastNullIndex = i;
} else {
break;
}
}
groupList = new ArrayList<>(groupList.subList(0, lastNullIndex));
return groupList;
If you think it can be further modified so as to allow for a better performance, let us know.
Im currently making a shopping store application, I have 6 classes. 1 for products where it defines the fields for products in the store, another for the shopping basket, one for the GUI and the rest for listeners.
I need to be able to run a method that runs through an array list and running the to.String method on it and returning it as String. Here is what I have at the moment,
private ArrayList<OrderItem> basket = new ArrayList<OrderItem>();
public String createArrayText () {
for (int i = 0; i < OrderItem.size(); i++){
if (i == OrderItem.size() - 1){
return ordersText ;
}
}
}
ordersText is a variable I made at the top of my shopping cart class.
This was my first start at it however I'm getting a error on the .size and obviously missing some key components.
One thing Extra is that each item created is added to the array list, each item has a unique order number.
Arrays.toString(basket);
Is that what you're looking for? If not, you need to explain a little better.
You generally speaking loop over a List like this (Java 7, it's called enhanced for loop):
for (TYPE TEMP_NAME : COLLECTION) {
}
That's the overall syntax. TYPE is the type of item in the list, yours are Object's in the given code. TEMP_NAME is the temporary name you want each entry to be referred as. COLLECTION is the list/array/stack/queue or other Collection.
Concretely:
for (Object o : basket) {
// if basket contains 10 entries the line will run 10 times. each new run contains a different object with name o
}
Normally when building strings it's preferred to use StringBuilder. We can skip that as it's "only" performance that you gain from it. We'll do it with a regular String. So:
Create an empty string that will get longer and longer
Loop the collection/array/list
Append each object's .toString() to the string from 1)
e.g.
String myReturnString = "";
for (Object o : basket) {
myReturnString = myReturnString + " // " + o.toString();
}
return myReturnString;
Notes:
Your loop with an index is fine. You can do it that way too, if you want to.
The line of code that appends the string has a " // " separator between each entry. You can pick whatever you like. You can also simplify it to be myReturnString += " // " + o.toString();
I want to create a Queue which should not allow duplicate elements and I should be able to access elements of this queue based on index. Please let me know how should I implement this?
Well it is clear that Java doesn't have the exact data structure matching your specification and requirement. The closest that can match your requirement is probably a LinkedHashSet. It is basically a Set (matching your unique items requirement) whose elements are kept in insertion-order (like a Queue) and to get an element by index you can use set.toArray() to get an array or create a list out of the set (however it will cost cost some extra memory).
I am planning to use ConcurrentLinkedQueue for my problem. Here is the sample code
import java.util.concurrent.ConcurrentLinkedQueue;
public class FinalQueue {
private ConcurrentLinkedQueue<String> queue;
public FinalQueue()
{
queue = new ConcurrentLinkedQueue<String>();
}
public synchronized void enqueue(String ipAddress)
{
if(!queue.contains(ipAddress))
queue.add(ipAddress);
}
public String dequeue()
{
return queue.poll();
}
public String toString()
{
return "" + queue;
}
/**
* #param args
*/
public static void main(String[] args) {
FinalQueue queue = new FinalQueue();
queue.enqueue("1.2.3.4");
queue.enqueue("2.3.4.5");
queue.enqueue("1.1.1.1");
queue.enqueue("1.2.3.4");
System.out.println(queue.toString());
System.out.println("Dequeue..." + queue.dequeue());
System.out.println("Dequeue..." + queue.dequeue());
System.out.println(queue.toString());
}
}
You could always just use an ArrayList. It's good for accessing elements based on index and when adding elements you can always just check if the ArrayList contains the element to be added. My initial instinct was to use a Set for the disallowing of duplicates, but the elements are Sets are not indexed. If you can find a way to index the elements in Sets, then that would be my recommendation.
Don't call it a queue because by definition a queue only is a first in first out data structure.
Depending upon your input values, i believe you should use an array and a hash function. The hash determines which index an element is located using its value and vice versa i.e. when given an index it returns the value contained in it.
Since you are using a hash, the repetition is avoided when a collision occurs i.e. you can check if a value previously existed in an index and if it's the same value or not.
C++ stl has a good class for set though java i don't think have one. But the point is set does not offer index based retrieval.