Methods For Partitioning Elements Of ArrayList

Feb 18, 2014

I'm new to object oriented programming, my previous experiences have been in C. I was given an assignment to implement an operation to transform a list of data by creating a partitioning algoritm.

import java.util.*;
public class Partition {
public static void partitionWithSetGet ( List<String> theCollectionOfData ) {
int i, j;
while(i <= j){
int Result = theCollectionOfData.get(i).compareTo(pivot);
int Result = theCollectionOfData.get(j).compareTo(pivot);

[code]....

I want to grasp the this concept in greater detail, then I can use the Java API to figure out the syntax!

View Replies


ADVERTISEMENT

Removing Elements From ArrayList

Aug 24, 2014

Referring Code 1, the book says line 16 of the code removes the element "Three" but line 17 does not remove the element "Four" because of Statement 1. The question is does remove(Object o) method invoke the == or the equals method because statement 1 and 2 seem to be in conflict

Statement 1:

Two objects are equal if their object references point to the same object. (which is nothing but definition of ==)

Statement 2:

The author refers to Statement 1 and says "As mentioned earlier, the method remove compares the objects for equality before removing it from ArrayList by calling method equals."

Java Code:

import java.util.ArrayList;
public class DeleteElementsFromArrayList {
public static void main(String args[]) {
ArrayList<StringBuilder> myArrList = new ArrayList<>();
StringBuilder sb1 = new StringBuilder("One");

[Code] ....

View Replies View Related

2D Arraylist Replace Specified Elements

May 11, 2015

I have a 2D arraylist, named as adjLists, which contains arraylists, containing values like these. Each two values are a "pair" and each third is a "flag" for the pair.

[278, 106, 0, 397, 36, 0, 59, 208, 0, 366, 221, 0]
[366, 221, 0, 397, 36, 0, 132, 390, 0, 278, 106, 0, 295, 0, 0]

I use code above to search for specified value pairs in these lists. vertexnum is the number of "sub arraylists" in adjLists.

for (int l = 0; l < vertexnum; l++) {
if (adjLists.get(l).get(0) == p.x && adjLists.get(l).get(1) == p.y) {
for (int h = 0; h < adjLists.get(l).size(); h += 3) {
for (int g = 0; g < vertexnum; g++) {
if ((vertexSprite[g].getX() + vertexSprite[g].getWidth() / 2) == adjLists.get(l).get(h)

[Code] ....

This code is to search exact values and replace their flag in every occurences. It can not find all the occurences of the values/pair in the lists, it replaces flag value only a few time. Value of score should be incremented with plus 1 after each found occurence, but this code increments it more than the number of matches.

View Replies View Related

Remove Multiple Elements From ArrayList?

Dec 27, 2014

I have an ArrayList of tens of thousands of elements, and want to remove the items at a given set of sorted indices like {1,5,29,318,499,583}. It seems like this operation could be performed in linear time and space by first finding a cumulative sum of the shifts needed to move everything to their right positions and then shifting every item. On the other hand, removing and shifting one by one would seem to require many more shifts. Is there a way to do this in Java's ArrayList?

View Replies View Related

How To Print Out All Elements Inside ArrayList

Oct 5, 2014

When this program runs it gives me

workbook.Contact@46e5590e
Number of contact: 1

The number of Contact that I input is just one when I run the program so the Number of contacts: 1 is correct, but it gives me workbook.Contact@46e5590e instead of printing out all the contacts stored inside the Contact class. Yes I do loop through the ArrayList and I also have a method inside the Contact class, the printNameAndPhone(), which prints out the name as well as the phone number but how do I incorporate the printNameAndPhone() method (located in the Contact class) inside the print() method (located inside the AddressBook class)???

Basically I'm asking how to access all the elements in the ArrayList<Contact> addressBook = new ArrayList<>();??My main class AddressBook

package addressbook;
import java.util.Scanner;
import java.util.ArrayList;
public class AddressBook {

[code]....

View Replies View Related

Method To Rearrange Elements In ArrayList?

Feb 24, 2015

how to read and understand the API's. I've got an array list and I was wondering if there was a method that can randomly re arrange the elements in terms of their index positions.

View Replies View Related

Accessing ArrayList Elements (Integer / String) And Put Them Into Hashtable

Mar 4, 2014

I have a data structure such as: ArrayList<ArrayList<Integer,String>

The data looks as [[1,2,3] [3,4] [99,98,40,32,45,65,1]]

I am trying to access each element and put them into a hashtable such as:

Hashtable<Integer,String>

With what I am doing below I am getting an out of bound error but can't see any other way of accessing the element

public static void hash(ArrayList<ArrayList<String>> list)
{
for(int i = 0; i < list.size(); i++)
{
int cnt = 0;
for(int y = 0; y < list.size(); y++)
{
if (! hashMap.containsValue(list.get(i).get(y)))
{
hashMap.put(cnt, list.get(i).get(y));
cnt++;
}
...

View Replies View Related

Accessing Object Methods Within Arraylist

Oct 14, 2014

Scanner in = new Scanner(System.in);
ArrayList<rand> selectedRand = new ArrayList<Rand>();
selectedRand.add(new Rand(in.nextLine()));

I have created the most minimal code for creating an array list. I was wondering what the basic syntax of accessing objects methods that are within an Array List. So if I was to trying and get a method such as [.returnValue,] how would this look within a Rand object that is declared in a Array List Since you cannot simply declare a new Rand object and say:

newRandObject.returnValue();

And you must go through the actual slotted portion of the array list. I have searched the web and my text book for an example however none are provided.

View Replies View Related

Sort ArrayList By Object Field WITHOUT Using CompareTo Methods?

Mar 9, 2014

I have a project where I must sort a collection of songs by a number of fields: year, rank, title and artist. in the project, we must use certain methods and we cannot add others without getting marked down. Here are the specific requirements:

Sorting

The -sortBy option will cause the output to be sorted by a particular field. If this option is specified, the output should be ordered according to the field named. If there are ties, the tied songs should appear in same order in which they were in the input file. If no -sortBy option is specified, the output should maintain the order of the input file.

public void sortYear()

Order the songs in this collection by year (ascending).public void sortRank()
Order the songs in this collection by rank (ascending).public void sortArtist()
Order the songs in this collection lexicographically by artist (ascending, case-insensitive).public void sortTitle()
Order the songs in this collection lexicographically by title (ascending, case-insensitive).

Here is the relevant code:

SongCollection Class
Java Code: import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.*;

[code]....

View Replies View Related

Accessing Arraylist Member Object Methods In Enhanced For Loop?

Feb 24, 2014

I've tried a couple ways to do it, and they don't work. I'm aiming for functionality like I got with the regular for loop, but from an enhanced for loop. Is this simply beyond the scope of an enhanced for loop, or am I just not getting the right syntax?

TestObject to1 = new TestObject("first", 11);
TestObject to2 = new TestObject("second", 12);
TestObject to3 = new TestObject("third", 13);
TestObject to4 = new TestObject("fourth", 14);
TestObject to5 = new TestObject();
List<TestObject> testList;
testList = new ArrayList<TestObject>();

[code]....

The TestObject class is simply an int and a String, with getters getInt and getString. It all works fine with the regular for loop.

edit: I should probably mention that I know what I have in the enhanced for loop now will only display the class name and the hash. I've tried adding the .getString and .getInt, and tried a few other ways to make it work. I just reverted to this because it compiles and runs

View Replies View Related

Declare Array Of 50 Elements Of Type Double - Print Output 10 Elements Per Line

Feb 5, 2015

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class array
{
public static void main(String[] args)

[Code] ...

Is there a way to write this, where, alpha is one array.

Write a program that declares an array "alpha" of 50 elements of type "double". Initialize the array so that the first 25 elements are equal to the square of the index variable and the last 25 elements are equal to three times the index variable. Output the array so that 10 elements per line are printed.

If I have an array of 50 integers, can I break that to read in lines of 10?

View Replies View Related

Add Elements To 2D Array Without Losing Elements

Jan 12, 2015

I am trying to make a 2d array that keeps track of comparison counts. what I have so far works ok but writes over the previous elements with 0. can't seem to find where I am re-initializing the previous elements.

//this is one of my fill sort arrays

public void fillSelectionArray(int index, long countSum) {
//rand = new Random( );
//for ( int i = 0; i < listsize; i++) {
selectionList[ index -1] = countSum;
// }

[Code] ....

I know I am missing something just not sure what.

View Replies View Related

Create Own ArrayList Using Collection Without Implementing ArrayList Itself

Feb 28, 2014

I'm trying to create my own arraylist using Collection. My program doesn't do anything. Obviously, I haven't a clue.

import java.util.Collection;
import java.util.Iterator;
public class MyArrayList<T> implements java.util.Collection<T> {
private int size = 4;
private T[] mArray;
public MyArrayList(String[] args) {

[Code] ....

View Replies View Related

How To Add Elements To A Map

Mar 13, 2015

I have a requirement to add elements to a map. But for, First iteration it inserts fine and for next iteration elements are overrided.

I am just wondering if there were append() in map or in any collections?

View Replies View Related

Why Not Getting All The Elements In TreeSet

Aug 1, 2014

public void createPersons() {
Random rand = new Random();
for(int index = 0; index < persons.length; index++) {
Person person = new Person(rand.nextInt(maxAge), persons[index]);
setOfPersons.add(person);

[Code] ....

setOfPersons is a TreeSet, persons[] is an array of strings that contains 10 names. Why printPersons() prints only the half names of setOfPersons?

Note. I do get the size of the TreeSet as 10...

View Replies View Related

Sum Of Array Elements?

May 4, 2015

What is the sum of the array ar elements after executing the following code?

int[] ar = {1,2,3,4,5};
for (int i=0; i<ar.length-1; i++)
if (i%2==0) ar[i]=i;

My professor says the answer is 12 i dont know how he got that answer

View Replies View Related

Max And Min Of Elements In Array

May 17, 2014

I cant get this code to work if wont find the right min and range and its printing out my max three times . This is what I got

public static void main(String[] args)
{
double [] Rainfall = new double[12];
Rainfall[0] = 77.4;
Rainfall[1] = 56;
Rainfall[2] = 61.8;
Rainfall[3] = 62.1;
Rainfall[4] = 57.1;

[Code] ....

View Replies View Related

Populating ArrayList Object With Nested ArrayList Object

Jul 8, 2014

I have stumbled onto a problem with ArrayLists (not sure if nested ArrayList objects would be a more accurate description) ....

As simply put as I can describe it, I have an Inventory class which creates an ArrayList of a Product superclass, which has two subclasses, PerishableProduct and ItemisedProduct.

By default, the program is meant to have a starting inventory, which is why I have added them in the constructor

public class Inventory {
private List<Product> products;
public Inventory() {
addProduct(new Product("Frying pan", 15, 20));
addProduct(new PerishableProduct("Apple", 5.8, 30, 7));
addProduct(new ItemisedProduct("Cereal", 5.8, 0));
// this is where I am having problems. Wanting to add
// objects to the ItemisedProduct's ArrayList for cereal.
}

Within the ItemisedProduct subclass is yet another ArrayList which is meant to hold serial numbers.

public class ItemisedProduct extends Product {
private ArrayList<String> serialNumbers = new ArrayList();
public ItemisedProduct(String name, double price, int qty) {
super(name, price, qty)

[Code] .....

My problem is that I do not know how to populate the serialNumbers ArrayList from the Inventory class' constructor. Because technically, quantity is defined by how many serial numbers are created.

View Replies View Related

How To Copy Elements Of One Array Into Another

Mar 29, 2015

I have two arrays

private ReservedBook[] reservedBooks;
private LibrarySystem[] libraryBooks;

The library array has two books and I want to copy one of them to the reserved books when you type in the ISBN

public void borrowBook(String ISBN)
{
int i = 0;
if(numberOfBooks < MAX_BOOKS-1)
{
if(libraryBooks[i].getBookISBN().equals(ISBN))
{
for(i=0;i<MAX_BOOKS-1;i++)
reservedBooks[i] = libraryBooks[i];
}
else System.out.println("There is no such book");
}
else System.out.println("You have reached the maximum number of allowed books");
}

It shows me error: incompatible types - LibrarySystem cannot be converted into ReservedBook. How can I fix it?

View Replies View Related

Java GUI With CRUD Elements

Jun 22, 2014

I would like to create a java gui (with CRUD elements) that connect to MySQL server DB and display a table records (also insert, edit, delete data to table), and I want to know how create such a gui.

View Replies View Related

Compare Elements Within Array?

Oct 27, 2014

So I am trying to create a code that searches if a word is square free. The user inputs a word (into an array) and then the code is suppose to see if it is square free. A word being square free means that the word doesn't contain any consecutive sub words. For example, "abcabc" is not a square free word because abc is repeated, but "abcdabc" is a square free word because there is a "d" separating the "abc".

So far I have this :

import java.util.Scanner;
public class A3Q2 {
public static void main(String[] args) {
// part (a) of the main
Scanner keyboard = new Scanner(System.in);

[Code] ....

I've been trying to experiment with different ways such as checking to see if there any duplicate elements such as,

public static char isSquareFree(char[] word){
for(char i = 1; i < word.length; i++) {
if(word[i] == word[i - 'a']) {
System.out.println("Duplicate: " + word[i]);
}
}
return word; }
}

And other methods but I'm just not getting it.

View Replies View Related

Adding Elements To A List

Feb 6, 2014

Here is a small part of my program

Java Code:

// for every attribute not mentioned in the rule r
enumAtt = ruleE.enumerateAttributes();
while (enumAtt.hasMoreElements()) {
Attribute attr = (Attribute) enumAtt.nextElement();
if (isMentionedIn(attr, r.m_test)) {continue;}
int M = attr.numValues();

[Code] ....

It repeats only the last rule , why is that !!!!!!

View Replies View Related

Reversing Elements In The List

Feb 14, 2014

i have the following code to reverse the elements of the list but i only print the last element each time

public void reverse(OrderedList<T> lister) {
OrderedList<T> listerCopy = lister;
for(int i=0;i<5;++i) {
T removed=removeFromBack(listerCopy);
System.out.printf("%s ", removed);

[Code] .....

View Replies View Related

Calculating Sum Of Elements Within JList

Mar 25, 2015

I'm currently in the process of creating a shopping cart simulation. The main GUI consists of two lists, one is a list of the inventory. (products stored within a .dat file which is automatically loaded upon launch) The other is blank and is to model my shopping basket. The idea is to be able to scan items from my inventory into the checkout basket. As this is happening i want a text field i created to dynamically update with the cost of all the items in the basket.

Below is the method for my scan button, which is supposed to perform the above :

public void actionPerformed(ActionEvent evt) {
//Get the newly added list values.
JList list = productList.getSelectedValuesList();
double totalAddedValue = 0.0;
double oldCartValue = 0.0;

[code]...

View Replies View Related

While Loop - Deleting Elements

Apr 27, 2014

ok so for class I'm supposed to Write a class DeleteElements that prints out an array and asks the user which number should be deleted and then deletes that number, if it exists from the array.

The first part tells me to

Step 1
o Start by simply searching the element.

o Pseudocode:
-Create an array and populate it with random positive integers.
-Print the array to show the user which elements the array contains.
-Use a WHILE loop to search the element—a WHILE loop is better than a FOR loop because you can stop when the element is found by using a Boolean value in the loop condition—and also keep track of the location where the
element might be found.
-If the element is not found, output the error message, “Number not found.”
-Otherwise output the message, “Number found at index #.” where # is the index where the element is.
-Print out the array.

Example of output:
34 65 12 76 45 39 86 71 67
Number to delete: 76
Number found at index 3

This is what I've got so far but I can't seem to get the "number not found part to print out only once".

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class DeleteElement {
public static final int ARR_LENGTH = 10;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random ran = new Random();

[Code] ....

Current output result if value does not exist:

61 89 52 16 20 71 37 91 4 36
Number to delete:
23
Number not found.
Number not found.
Number not found.
Number not found.
Number not found.
Number not found.
Number not found.
Number not found.
Number not found.
Number not found.
Current output result if value exists:

97 48 51 22 89 5 42 97 43 96
Number to delete:
89
Number found at index 4

Maybe I'm not understanding the part about the boolean value.

View Replies View Related

Printing Array Elements In Java

Oct 15, 2014

I have tried to print array elements using standard print statement. I am getting errors. How to print them. Here is my code:

class arrayEx1{
public static void main(String args[]) {
int a[]=new int[3]; //Declaring Single Diomentional Array
a[0]=10;
a[1]=20;
a[2]=30;
int total=a[0]+a[1]+a[2];
System.out.println("Values stored in a[0],a[1],a[2]elements are :" + a[0] a[1] a[2]);
System.out.println("Total values of a[0],a[1],a[2]elements is :"+ total);
}
}

if i give comma (,) in between above print stament (print statement 1) stil i am getting errors.

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved