Appropriate Way Of Populating Collection Through Instance
Feb 23, 2015
I have a method that accepts JSONArray as parameter and returns the values of it as ArrayList Object. My question which of these ways is appropriate in populating the ArrayList object this method populates the arraylist upon creation of object (I don't know what the right term to use, but as netbeans IDE suggest, JSONArray object should be final since it was used in inner class.).
private List<String> getStringList(final JSONArray jsonArr) {
return new ArrayList<String>() {
{
try {
for (int i = 0; i < jsonArr.length(); i++) {
add(jsonArr.getString(i));
}
} catch (JSONException ex) {
ex.printStackTrace();
}
}
};
}
this second method is the usual way of populating collection
private List<String> getStringList(JSONArray jsonArr) {
List<String> strList = new ArrayList<String>();
try {
for (int i = 0; i < jsonArr.length(); i++) {
strList.add(jsonArr.getString(i));
}
} catch (JSONException ex) {
ex.printStackTrace();
}
}
What are the advantages and disadvantages between the two? like which is faster? or which consumed larger memory?
I am having a hard time trying to wrap my head around trying to get a couple of columns in a datatable populated with values from a @OneToMany collection. The concept is simple but my brain refuses to grasp it!! I will try to make this brief...
I have several forms built with primefaces 3.5 using NetBeans 8 IDE on a JBoss EAP 6.21 server, and JPA 2.1 annotations. Data is extracted from an Oracle 11 database, which consists of several lookup tables, as well as a primary table and secondary table. Using the EntityManager createQuery method I query the database, which of course returns a resultset. The query grabs all records from the primary, as well as values from 2 specific columns of the secondary database, based on search criteria entered by the user on a primefaces search form. The returned results are then iterated through, this is where I am trying to get the values from the secondary table to populate specific fields in the datatable.Here is the applicable code from the list.xhtml form containing the datatable:
As odd as the code may look (and I will completely understand anyone cringing as to some of the coding methods I use), specifically with the ui:repeat tags nested inside the datatable tag of the list.xhtml form, I strangely do see the values from the secondary table showing up in the form showing the results in a datatable. However, when the user clicks on a specific record in the returned resultset listed in the datatable, another form is opened and populated with the values from the datatable, but the 2 fields on that form that should be populated with the 2 values I referred to before from the secondary table (i.e. policy1Num and totalPayoutAmt) do not have the values in them.
This is partly because I have those 2 fields in the editable form pointing to the managed bean of the secondary table (code from that bean not shown here), rather than the same "polNum. policy1 Num" and "totPayout.totalPayoutAmt" var I am using in the list.xhtml form. How those values are being successfully returned into the datatable of the list.xhtml form - I happened to "stumble" across the use of the "polNum" and "totPayout" vars with the "policy Payment Collection" list. I do not know how to do the same thing for those 2 fields in the editable form.how a datatable gets populated, specifically with values in a @OneToMany collection,
This is the method public void populateMatrices(int [][]mat1, int [][]mat2). I know how to do it for one matrix, but what do we do for the additional matrix? Here is the code I have so far.
for (int row =0; row<mat1.length;row++){ for (int column = 0; column<mat1[row].length;column++){ mat1[row][column]=1 + (int)(Math.random()*5);
I am trying to populate a Jlist for information stored on a database. The database contains football club names, but instead of being populated with their names it just has a hexadecimal reference ( Club@183357c4 ) for each club object.
I have been given a task to do, which is to create a memberList and populate it with data. The constructor has been created with me, but I am required to add code to display the memberList. I am also required to creates a method to display members.This is the method I created:
/** * Populates the list of members. * Displays the membership numbers and names of library members in ascending membership number order. * The first member is selected by default. */ public void displayMembers() { initComponents(); library = new LibraryCoord(); Collection<Member> Member = library.getMembers(); memberList.setListData(Member); memberList.setSelectedIndex(0);
[code]....
The code below TO DO is mine.What is meant to happen when I run the project is for a GUI form list to show the members of memberList. However, it does not.
I'm not sure this is right... Is there a way to automate this process? What if we have arrays like int[][][] Terms? This is terrible... Is there a software tool for this?
I have created Person.java with the following attributes:
private String firstName; private String lastName; private int age;
My main method parses the XML, loops through each person, and gets the attributes for each.
I need to create instances of my Person class. I could write something like this:
Person person = new Person(); for (int i = 0; i < attributes.getLength; i++) { if (attribute.getName(i) = "firstname") { person.firstName = attribute.getValue(i);} if (attribute.getName(i) = "lastname") { person.lastName = attribute.getValue(i); } if (attribute.getName(i) = "age") { person.age = attribute.getValue(i); } }
Since my actual XML has quite a few attributes, I would rather do something like this:
Person person = new Person(); for (int i = 0; i < attributes.getLength(); i++) { person[attribute.getName(i)] = attribute.getValue(i); }
import java.io.*; import java.util.Scanner; public class asciiFile { int height; int width; Scanner input; char[][] poop; public asciiFile(File f) throws FileNotFoundException{ //constructor
[code]...
The constructor is supposed to take an ASCII file, take the numbers in the file, and populate a 2D array with the numbers in the file.
For some reason, the for loop I use to populate the array works outside of the constructor. When I put it in one of the methods, it runs normally. However, when I keep it in the constructor, I get the following error:
Exception in thread "main" java.lang.NullPointerException
My code runs and populates an arraylist. However my break statement, while stopping the loop ends up being added to the arraylist. And I'm not sure how to fix this error.
public static void main(String args[]) throws Exception { // declaring variables String input = ""; // creating array list ArrayList<String> nameList = new ArrayList<String>();
We are getting "Code too large" compilation error for one of our class. This class contains public String fields for label ID and value. We use this class for localization, except for English all other language labels come from .properties files.
The reason we are getting this error is because we have a static block in which using reflection we are populating a HashMap with all public fields and their value. The number of fields have gone up to the extinct where we are crossing the 64K limit for a static method. One of the most feasible solution was to use .properties files for English labels as well.
I will be calling this class MyLabels. We defined a super class for MyLabels called MyLabelsExt. And now we are adding labels into the super class instead of the MyLabels. By running some tests we confirmed that the map that we initialize in MyLables class contains all the fields from both MyLabels and MyLabelsExt class.
How is the 64K limit error not coming if the labels are defined in a super class. Does that mean Java is able to identify that some of the fields are coming from parent class, and that is being treated as separate from the child class. And how is the map that we initialize having all the value.
I have small project to be implemented in Java, which, expected the management of a parking.
The project has a class abstract Vehicle, whence derive three classes: Car, Motorcycle, Heavy Vehicles; the cost estimated time for the 3 types of vehicles are: 2€ for Cars, 1€ for Motorcycle and 5€ for H.V.
In addition, in class Ticket will be stored the arrival time of the customer and the characteristics of his vehicle.
Finally, in the class Parking(which provides 80 places available), here it should be added the various types of vehicles.
Now, I though of using an Collection, as Set.. So that they can not, two Vheicle with same license plate.
I am using mysql database and I have downloaded the library also I have managed to get the database connection and query working. I need to know if I need to create separate classes to add/remove/edit items and view items? Do I need to put my database connection script in every class that I create or should I create methods for both the connection and the queries that will be called in the additional classes or methods that I have?
Below is what I have written so far and it is working, I will change the database and query soon to reflect the task I need to do because I have followed a tutorial.
Java Code:
/** * cdCollection.java */ package org.com.mm00422_prototype; //Import for the SQL package import java.sql.*;
//Registering the JDBC driver //Class.forName("com.mysql.jdbc.Driver");
The last line seems half cut. Does that indicate that there is memory leak in my application? I have not seen the app throwing the out of memory error.
I need to create an algorithm that finds the common element(s) in all arrays that has a signature of public Comparable[] findCommonElements(Object[] collection) that has an efficiency of at most O(knlogn), uses a query array, and accepts as input a collection of arrays. I am aware my time would be better spent learning how to use array lists and hash sets, but I am supposed to use concepts already covered, and these have not been.
I feel like this code should work, but it is returning null for the array of common elements. Which means it obviously is not working correctly. I am also likely going to need implementing the sort algorithm, but I wanted to get the part of finding the common elements set first.
public class CommonElements2<T extends Comparable<T>> { Comparable[] tempArr; Comparable[] common; Comparable[] queryArray; /* sort algorithm goes here */ public Comparable[] findCommonElements(Object[] collections)
Write a function (or functions) that given a collection of files will produce a sum of integers from each line of each file. Each file can have any number of lines from 1 to N. Each line can contain only one integer and no other alphanumeric characters. All of the numbers from all of the files should be added to the final result. The result is just one number.
17/03/2015 09:38:39 AM 17/03/2015 10:52:26 AM 10/03/2015 08:30:56 AM 02/03/2015 09:18:10 AM 02/03/2015 09:37:23 AM 02/03/2015 11:25:01 AM 02/03/2015 11:29:00 AM 02/03/2015 11:42:38 AM 02/03/2015 12:04:39 PM 02/03/2015 12:09:05 PM 02/03/2015 01:17:09 PM 02/03/2015 01:29:08 PM
I want them to sort them as per below result: (Same date one should be sort by timestamp)
17/03/2015 10:52:26 AM 17/03/2015 09:38:39 AM 10/03/2015 08:30:56 AM 02/03/2015 01:29:08 PM 02/03/2015 01:17:09 PM 02/03/2015 12:09:05 PM 02/03/2015 12:04:39 PM 02/03/2015 11:42:38 AM 02/03/2015 11:29:00 AM 02/03/2015 11:25:01 AM 02/03/2015 09:37:23 AM 02/03/2015 09:18:10 AM
I tried using Collection.sort using compareTo but result is not expected...
public class Person { private String name; private int age; public Person (String name, int age) { this.name = name; this.age = age;
[Code] .....
And I need to write a simple main method that creates lots of instances of the Person class and adds them to a generic instantiation of a Collection (ArrayList). And I need to make it so I as a programmer can define how many instances to create.
I am looking at a snippet of code in my "learning Java 4th edition" by Orielly and there is a small snipped of code which says:
Java Code: Date date = new Date(); List list = new ArrayList(); list.add( date ); ..
Date firstElement = (Date)list.get(0); // Is the cast correct? Maybe. mh_sh_highlight_all('java'); so I am typing the same thing in my compiler in a small Driver class and for some reason I have an error and Im dumbfounded...
17/03/2015 09:38:39 AM 17/03/2015 10:52:26 AM 10/03/2015 08:30:56 AM 02/03/2015 09:18:10 AM 02/03/2015 09:37:23 AM 02/03/2015 11:25:01 AM 02/03/2015 11:29:00 AM 02/03/2015 11:42:38 AM 02/03/2015 12:04:39 PM 02/03/2015 12:09:05 PM 02/03/2015 01:17:09 PM 02/03/2015 01:29:08 PM
I want them to sort them as per below result: (Same date one should be sort by timestamp)
17/03/2015 10:52:26 AM 17/03/2015 09:38:39 AM 10/03/2015 08:30:56 AM 02/03/2015 01:29:08 PM 02/03/2015 01:17:09 PM 02/03/2015 12:09:05 PM 02/03/2015 12:04:39 PM 02/03/2015 11:42:38 AM 02/03/2015 11:29:00 AM 02/03/2015 11:25:01 AM 02/03/2015 09:37:23 AM 02/03/2015 09:18:10 AM
I tried using Collection.sort using compareTo but result is not expected.
I'm doing a project with very defined requirements. Input and output will be done to and from a file. Both the input and output files should have the same format. Each file will consist of a series of lines formatted as follows:
Year Rank Artist Title
That is, each line of the file will consist of the year, rank, artist, and title of a single song, with each of the fields separated by tabs ( ). Output files must maintain this format—you should be able to use the output file of one run of the program as the input to another run.
The first part of my project is to make a Song class, with 6 methods:
public static Song parse(String s) { //Parse a string of the form “Year Rank Artist Title” and create a Song object with the given values. } public int getYear() { //returns the year of the song } public int getRank() { //returns the rank of the song
[Code] .....
So far, I have worked out my Song class like this:
Java Code:
import java.util.Scanner; public class Song { private int year; private int rank; private String artist; private String title;
[Code] ....
I know there's definitely a problem with my parsing, as I am getting the
Exception in thread "main" java.util.NoSuchElementException
when I attempt to input a test String at my variables.
Should I try using StringTokenizer and Integer.parseInt()? I think that perhaps the reason why an error is occuring is because the String is being parsed into Strings and there are no int values to be inputted into the year and rank variables.