Recursion: powerset , returning an array list of subsets
Hi, i've checked hundreds of webpages, but i still can;t figure out how to create a recursive method that returns the powersets of a set.
The sets returned are of type Arraylists
ex: set {1, 2, 3} returns an arrayList of arrayLists: { { }, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3} }.
The code should look somewhat like that: but the recursive call does not work...
ArrayList powerSet(ArrayList s) {
ArrayList result = new ArrayList();
if (s.size() == 1) { // base case
// return a new ArrayList containing just s
ArrayList tempAL = new ArrayList();
tempAL.add(s);
result.add(tempAL);
return result;
else {
Integer last = (Integer)s.get(s.size()-1); // separate the first character from the rest
ArrayList rest = new ArrayList(); // remainder of the set
rest.addAll(s);
rest.remove(rest.size()-1); // get rid off element "last"
// recursively call method on the remainder of the set
ArrayList L = new ArrayList();
L.add( powerSet(rest) ); // recursively call method on the remainder of the set
// return the set composed of the Union of
// the powerset of the set without the element (from the recursive call)
result.addAll(L);
// return the same set but
// with each element therein unioned with the element initially taken out
for(int i=0; i< L.size(); i++) {
ArrayList tmp = new ArrayList();
tmp.addAll( (ArrayList)L.get(i) );
tmp.add(last); // adding the element initially taken out
result.add(tmp);
return result;
Please someone help me. I know there has to be many errors during recursion. it's like i can't grasp the concept.
Thx a lot :)
Edited by: jonaphin on Oct 18, 2007 12:01 AM
btw, the output is: arraylists of arraylists of arraylists, depending on the depth of the recursion. argh :(
[[[[[[1]]], [[[1]], 2]], [[[[1]]], [[[1]], 2], 3]], [[[[[1]]], [[[1]], 2]], [[[[1]]], [[[1]], 2], 3], 4]]
I think he changed
if (s.size() == 1) { // base case
to
if (s.size() == 0) { // base case
Also, jonaphin are you in Alexander Pelin's Data Structure Class at FIU? Because, amazingly enough... this is the exact assignment that has to get handed in today! (October 18) lol ;)
Similar Messages
-
Is possible to pass array/list as parameter in TopLink StoredProcedureCall?
Hi, We need to pass an array/List/Vector of values (each value is a 10 character string) into TopLink's StoredProcedureCall. The maximum number of elements on the list is 3,000 (3,000 * 10 = 30,000 characters).
This exposed two questions:
1. Is it possible to pass a Vector as a parameter in TopLink's StoredProcedureCall, such as
StoredProcedureCall call = new StoredProcedureCall();
call.setProcedureName("STORED_PROCEDURE_NAME");
call.addNamedArgument("PERSON_CODE");
Vector strVect = new Vector(3000);
strVect.add(“ab-gthhjko”);
strVect.add(“cd-gthhjko”);
strVect.add(“ef-gthhjko”);
Vector parameters = new Vector();
parameters.addElement(strVect);
session.executeQuery(query,parameters);
2. If the answer on previous question is yes:
- How this parameter has to be defined in Oracle’s Stored Procedure?
- What is the maximum number of elements/bytes that can be passed into the vector?
The best way that we have found so far was to use single string as a parameter. The individual values would be delimited by comma, such as "ab-gthhjko,cd-gthhjko,ef-gthhjko..."
However, in this case concern is the size that can be 3,000 * 11 = 33, 000 characters. The maximum size of VARCHAR2 is 4000, so we would need to break calls in chunks (max 9 chunks).
Is there any other/more optimal way to do this?
Thanks for your help!
ZoranHello,
No, you cannot currently pass a vector of objects as a parameter to a stored procedure. JDBC will not take a vector as an argument unless you want it to serialize it (ie a blob) .
The Oracle database though does have support for struct types and varray types. So you could define a stored procedure to take a VARRAY of strings/varchar, and use that stored procedure through TopLink. For instance:
StoredProcedureCall call = new StoredProcedureCall();
call.setProcedureName("STORED_PROCEDURE_NAME");
call.addNamedArgument("PERSON_CODE");
oracle.sql.ArrayDescriptor descriptor = new oracle.sql.ArrayDescriptor("ARRAYTYPE_NAME", dbconnection);
oracle.sql.ARRAY dbarray = new oracle.sql.ARRAY(descriptor, dbconnection, dataArray);
Vector parameters = new Vector();
parameters.addElement(dbarray);
session.executeQuery(query,parameters);This will work for any values as long as you are not going to pass in null as a value as the driver can determine the type from the object.
dataArray is an Object array consisting of your String objects.
For output or inoutput parameters you need to set the type and typename as well:
sqlcall.addUnamedInOutputArgument("PERSON_CODE", "PERSON_CODE", Types.ARRAY, "ARRAYTYPE_NAME"); which will take a VARRAY and return a VARRAY type object.
The next major release of TopLink will support taking in a vector of strings and performing the conversion to a VARRAY for you, as well as returning a vector instead of a VARRAY for out arguments.
Check out thread
Using VARRAYs as parameters to a Stored Procedure
showing an example on how to get the conection to create the varray, as well as
http://www.oracle.com/technology/sample_code/tech/java/codesnippet/jdbc/varray/index.html on using Varrays in Oracle, though I'm sure the database docs might have more information.
Best Regards,
Chris -
Adding two array lists together and a text file to an array list
I'm having problems coding these two methods... Could someone explain how to do this? I can't find information on it anywhere... :(
"MagazineList" is the class I'm coding in right now, and I already declared "list" as an array list of another class called "Magazine".
public boolean addAll(MagazineList magazines)
if (list == magazines) {
return false;
else {
list.addAll(magazines);
return true;
public boolean addAll(String filename)
Scanner in = ResourceUtil.openFileScanner(filename);
if (in == null) {
return false;
String line = source.nextLine();
while (!line.equals("")) {
list.add(Magazine(source));
in.close();
}I assume "addAll(MagazineList magazines)" is defined in the MagazineList class?
Then,
list.addAll(magazines);probably needs to be something like:
list.addAll(magazines.list);This uses the private variable ( should be private) list from the input MagazineList, and adds all of those Magazine objects to the list in the current MagazineList.
But, yes, describe your problems more clearly, and you'll get better answers more quickly (because people will be able to understand you and give you a suggestion without asking you another question first). -
function Recurse($RootFolder,$List) {
$Context.Load($RootFolder)
$Context.Load($RootFolder.Folders)
$Context.ExecuteQuery()
foreach($folder in $RootFolder.Folders)
if($Folder.Name -ne "Forms")
$Context.Load($folder)
$Context.Load($folder.Files)
$Context.ExecuteQuery()
foreach($file in $folder.Files)
$FileCollection +=
$file
Recurse $folder $List
Recurse $folder.ParentFolder $List
Return $FileCollection
I am trying to traverse through SharePoint Online Site collection using Powershell CSOM. I am able to go to the last folder from the root folder which is 2-3 levels down. But I could not search through all the document libraries as it gets struck to one
of the last document library.Below script is working for me. I can now traverse through all the folders and subfolders including the root folders to fetch all the files using Powershell and CSOM.
#function begins
function Recurse($RootFolder) {
$Context.Load($RootFolder)
$Context.Load($RootFolder.Folders)
$Context.ExecuteQuery()
$Context.Load($RootFolder.Files)
$Context.ExecuteQuery()
$resultCollection = @()
foreach($file in $RootFolder.Files)
$resultCollection += $file
foreach($folder in $RootFolder.Folders)
if($Folder.Name -ne "Forms")
Recurse $folder
Return $resultCollection
# Function ends -
Accessing Array and Iterating Array list
Hi,
I want some advice on how to iterate through a Array list which has an array of tasks/processes and make calls to the corresponding subprocess for each element in the list using BPM 11g
We are looking for a BPMN approach.
Any example or ideas would be of great help.
My requirement states that i will get a list of tasks from a Rules Engine and i have to use BPM to iterate through the tasks and make calls to each tasks(which is a subprocess call).
In Oracle BPM 11g I would like to use a multi-instance subprocess to send a task to a user for each item in an array. There are an unknown number of rows in the array. Does anyone have a good example of how to do this?
I am using BPM Oracle 11g but any help 10 will also help us.
I am reposting again this question , hoping that someone will help us
ThanksOthers probably are getting it, but I'm not really sure what it is that you're tyring to do with the list of instances.
I'm getting lost in two areas. First, you mentioned you have a rules engine returning a list of instances. Mostly out of curiosity - why do you have an array of instances being created by a rules engine? What is the use case? Asking because I'm sure to learn something new from you on this - I'm used to seeing a lot of things coming back from an invoked rule, but never an array of instances before.
Second (sure you know this), in both 10g and 11g there is a Split-N activity that you can use to parse (as the name implies) "N" number of instances. This "N" is discoverable at runtime. If you have 14 instances in your array at runtime, it would go into a Split-N activity and 14 instances would automatically be spawned. The 14 instances would flow from the Split-N to its corresponding Join activity in the process.
Dan -
Need help finding the sum of an array list
I'm making a mock up of iTunes, I suppose, for class. My only issue is that I can't figure out how to add all the durations of each sound file when it's stated in the array.
I've put the part I'm having trouble with in bold, it is located in the Jpod class. We're using a program called BlueJ for coding, which is why the commenting is slightly odd.
import java.applet.*;
import java.io.*;
import java.net.*;
public class SoundPlayer
public SoundPlayer(String fileName, int duration)
AudioClip testClip;
URL testUrl;
System.out.println("Playing " + fileName);
try{
testUrl=new URL("file:" + new File(".").getCanonicalPath() + "/" + fileName);
testClip=Applet.newAudioClip(testUrl);
testClip.play();
Thread.sleep(duration*1000);
testClip.stop();
}catch(Exception e){ System.out.println(e.toString()); }
public class Sound
private String author;
private String fileName;
private int duration;
* Constructor for objects of class Sound
public Sound(String newAuthor, String newFileName, int newDuration)
// initialise instance variables
author = newAuthor;
fileName = newFileName;
duration = newDuration;
* Returns the duration of the sound file
* @return duration of the sound file
public int getDuration()
// returns duration
return duration;
* Returns the author of the sound file
* @return author of the sound file
public String getAuthor()
//returns author
return author;
* Prints the author, filename, and duration
public void printSound()
System.out.println("Author: " + author + " File name: " + fileName + " Duration: " + duration);
* Plays the sound
* @return sound file
public void playSound()
new SoundPlayer("Lab4.wav",3);
import java.util.ArrayList;
import java.util.Iterator;
public class Jpod
// instance variables - replace the example below with your own
private ArrayList<Sound> playlists;
* Constructor for objects of class Jpod
public Jpod()
playlists = new ArrayList<Sound>();
* Adds a sound to the playlist
* @param sound of type Sound
public void addSound(Sound sound)
// inserts the sound into the playlist
playlists.add(sound);
* Adds 3 sounds to a playlist
public void createPlayList()
Sound s;
s = new Sound("Microsoft", "Lab4.wav", 2);
addSound(s);
s = new Sound("Dr. Evil", "DrEvil.wav", 4);
addSound(s);
s = new Sound("Arnold Schwarzenegger", "Terminator.wav", 2);
addSound(s);
* Remove desired sound object
* @param indexNumber The number of the sound object to be removed
public void removeSound(int indexNumber)
if(indexNumber < 0){
//Not a valid index number - do nothing
else if(indexNumber < playlists.size()){
//Valid indexNumber
playlists.remove(indexNumber);
else {
//Not a valid index number - do nothing
* Show the sound object
* @param indexNumber The number of the sound object to be shown
public void getSound(int indexNumber)
if(indexNumber < 0){
//Not a valid index number - do nothing
else if(indexNumber < playlists.size()){
//Valid indexNumber
System.out.println(playlists.get(indexNumber));
else {
//Not a valid index number - do nothing
* @return The number of sounds in the playlist
public int getSize()
return playlists.size();
* List all sounds in the playlist
public void indexPrintList()
for(Sound playlist : playlists) {
playlist.printSound();
* Lists all sounds in the playlist using an iterator
public void iteratorPrintList()
Iterator<Sound> iter = playlists.iterator();
while(iter.hasNext()) {
((Sound)iter.next()).printSound();
* Gives the total duration of all sounds in the playlist
*public void totalDuration()*
*//currently prints all durations - still working on sum*
*for(Sound playlist : playlists) {*
*System.out.println(playlist.getDuration());*
* Plays through all the sounds in the playlist
* Extra Credit
public void indexPlayList()
for(Sound playlist : playlists) {
playlist.playSound();
* Plays through all sounds in the playlist using an iterator
* Extra Credit
public void iteratorPlayList()
Iterator<Sound> iter = playlists.iterator();
while(iter.hasNext()) {
((Sound)iter.next()).playSound();
}not sure if I'm missing something here, but this could possibly be solved by initializing a variable to 0 before the for loop, and then adding each duration to this variable as you loop. This seems too trivial a solution though. Again, I may be missing something here.
something simple like:
public void calcSum()
int i = 0;
for(Fubar foo: fooList) {
i += foo.getLength();
System.out.println("Sum = " + i);
}Edited by: petes1234 on Oct 23, 2007 9:09 AM -
How to get keep one column as a key and the other columns as a array list
Hello,
I am really new to Java...I am trying to read a text file containing different columns separated by comma and then create a hash map for the first column (key) and then rest as a array list for the key.I am not able to create the hash map and the corresponding key.Could someone help me in this regard.
The text document is :
AcctNo,AcctMngr,AcctType,ProdList,Volume,AcctPrice,Returns
12345,Vikram,2,MSFS:IBM:XYZ:MAN,28000,4500,1.25
53278,Anand,1,PLYS:AIX:YET:WON,85000,8500,2.32
94005,Vincent,3,UTIL:FLY:YEL:WIN,67000,5600,3.21
45000,Abhishek,2,WENS:KYL:MEN:ABS,34000,9800,4.21
76000,Chris,3,MENS:IBM:ROC:QUE,25000,2500,2.15
67000,Kiran,4,FORS:ITI:MOC:REM,32000,3500,1.54
87000,Rohit,2,MSNF:IIT:HOT:ROC,54000,5400,4,23
45600,Sathyan,3,HELP:FOR:PRO:GRA,65000,3400,2,1.98
84600,Vinay,4,PLZE:TES:ROC:WEN,76000,7300,3,4.32
65000,Venkat,2,HETT:WEL:SEE:RED,89000,9800,1,3.23
and the code which i have so far is
import java.io.*;
import java.util.*;
class SearchHash {
public static void main (String args[]) {
int i=0;
int j=0;
Object newKey = new Object();
Object newValue = new Object();
Map map1 = new HashMap();
ArrayList a1 = new ArrayList();
String val;
try {
BufferedReader br1 = new BufferedReader ( new FileReader ( new File ("progress.txt")));
String s="";
s = br1.readLine();
while (s!=null) {
StringTokenizer st = new StringTokenizer (s ,",");
int k=0;
while (st.hasMoreTokens()) {
while (k<=6) {
val= st.nextToken();
if (k==0) {
newKey = val;
else{
newValue = val;
a1.add(newValue);
k = k+ 1;
map1.put(newKey,a1);
map1.put(newKey,a1);
a1.clear();
s = br1.readLine();
// System.out.println(map1);
}catch (Exception e) {
System.out.println("Exception Raised : " + e);
Thanks.,...Array? Don't live in object denial. Define a class (Account?) and parse each line as an Account object. Then you put them into a Map<Integer, Account> by their account number.
-
External java function that should return String array
Hi everyone,
I have a split function in plsql that takes 10 times longer a java tokenizer function that i was written. So, i want to use java external function to split my plsql strings into pieces.
I can write a java external procedure that returns types like int, float and String types. I have no problem about it.
My problem is returning an array of strings. I found a book that has an example about how can we get directory list in plsql with java external procedure.
(code)
import java.io.File;
import java.sql.*;
import oracle.sql.*;
import oracle.jdbc.*;
public class JFile {
public static oracle.sql.ARRAY dirlist (String dir)
throws java.sql.SQLException
Connection conn = new OracleDriver().defaultConnection( );
ArrayDescriptor arraydesc =
ArrayDescriptor.createDescriptor ("DIRLIST_T", conn);
File myDir = new File (dir);
String[] filesList = myDir.list( );
ARRAY dirArray = new ARRAY(arraydesc, conn, filesList);
return dirArray;
CREATE OR REPLACE FUNCTION dirlist (dir IN VARCHAR2)
RETURN dirlist_t
AS
LANGUAGE JAVA
NAME 'myFile.dirlist(java.lang.String) return oracle.sql.ARRARY';
(code)
I could compile this source file in localhost but not remotehost. There are jar files ( import oracle.sql.*; import oracle.jdbc.*; ) that should be added to remote classpath. ( others have already added java classpath ). But, which classpath i should add? Oracle has own JVM and Classpath, probably i should upload these jar files to oracle classpath. Am i wrong? How can i do? Can you explain in detail? How can i return string array from java external function in Oracle ?
I am using Oracle 11.1.0.7 on Solaris Sparc Machine.Hi,
What do you mean "compile in remote host"
Aren't you using the loadjava tool? - that should be enough, the RDBMS already "has" the jars needed.
[A must read|http://download.oracle.com/docs/cd/B28359_01/java.111/b31225/chone.htm#BABCFIIF]
Regards
Peter -
How to find and display the posistion in an array list
hi all,
i know this is proballly simple but i have an arraylist where every time someone connects to my system it adds them to an arraylist, how can i post back somelike like hi user "1" thanks for connecting and so on. i just dont understand how to find their unique posistion in the array list and display it as a number.
any help would be greatSo to be clear...
You have an arraylist of connections .... for example
ArrayList<ConnectedPeople> connPplArr = new ArrayList();And then each time someone connects you would add a connected people object to the arraylist.
ConnectedPeople, migh contain username etc etc.
You could then do:
ConnectedPeople newConnection..... ;
int index = connPplArr.indexOf( newConnection );
if(int == -1){
add them to your array
index = connPplArr.size();
return "Hello user "+ index;That what you mean?
I know some of it is sudo code, but have I understood your problem?
Edited by: Azzer_Mac on Apr 29, 2008 2:20 AM
Edited by: Azzer_Mac on Apr 29, 2008 2:20 AM -
A suggestion : use "loop array list" instead of ArrayList / LinkedList
ArrayList is good at:
get / set by index : O(1)
appending : O(log(n))
remove last : O(1)
and very bad at:
add middle : O(n)
remove from middle : O(n)
LinkedList is good at:
fast remove from middle, if your iteraror already goes there : O(1)
convenient methods : addFirst, addLast, removeFirst, removeLast : O(1)
and very bad at :
get / set by index : O(n)
here I want to make a suggestion : use "loop array list" instead of the ArrayList and LinkedList.
a "loop array list" is based on array, just like ArrayList. But it has 2 member-variables : the start position, and the real size. the start position can be anywhere within array.length. an element of index "i" is stored in array[ start + i ], and when (start + i > array.length), loop to the beginning of the array; when (start + i < 0), loop to the end of the array.
this "loop array list" has all the good sides:
get / set by index : O(1)
add first / last : O(log(n))
remove first / last : O(log(n))
add / remove from middle : O(n)
(note : because we shrink the backup-array when the real size is too small, add / remove operation take O(log(n)) now.)
the only problem is : add / remove from middle. let's take a look at it.
1. the LinkedList does NOT really add/remove from middle in O(1), you has to locate the element, which is O(n).
2. O(n) is acceptable, O(n^2) is not acceptable. try this : keep removing first element from an very big ArrayList ( size>10^6 ) until it's empty.
the fact is, any list can perform batch-remove / batch-add operation in O(n) instead of O(n^2). it's easy : allocate a new list, iterate the original list, copy the element into the new list if condition is satisfied.
so, instead of "remove from middle", what we need is a new methods : removeAllByCondition( Condition condition ), and now the batch-remove operation can be done in O(n)
here is an implementation of mine. I've tested it on my computer( 512mem + 2G cpu, win2k + jdk1.5 ), it's amazing, just a little slower then ArrayList when add last, and a liitle slower then LinkedList when batch-remove. in all other cases, it's far more better then those 2 kinds of List.
// source code : List2
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
public final class List2<T> extends AbstractList<T> {
private static int initialArrayLength = 4;
private T[] array;
private int start;
private int size;
private void init( T[] newArray, int start_a, int size_a ) {
array = newArray;
start = start_a;
size = size_a;
@SuppressWarnings("unchecked")
private void init() {
init( (T[]) new Object[ initialArrayLength ], 0, 0 );
public List2() {
init();
@SuppressWarnings("unchecked")
public List2( Collection<? extends T> collection ) {
init(
collection.toArray( (T[]) new Object[ collection.size() * 11 / 10 + 1 ] ),
0,
collection.size()
private List2( T[] array_a, int start_a, int size_a ) {
init( array_a, start_a, size_a );
@SuppressWarnings("unchecked")
public static <TT> List2<TT> createV( TT... elements ) {
TT[] array = (TT[]) new Object[ elements.length * 11 / 10 + 1 ];
System.arraycopy( elements, 0, array, 0, elements.length );
return new List2<TT>( array, 0, elements.length );
public static List2<Double> create( double... elements ) {
Double[] array = new Double[ elements.length * 11 / 10 + 1 ];
for( int i=0; i < elements.length; i++ )
array[i] = elements;
return new List2<Double>( array, 0, elements.length );
public static List2<Integer> create( int... elements ) {
Integer[] array2 = new Integer[ elements.length * 11 / 10 + 1 ];
for( int i=0; i < elements.length; i++ )
array2[i] = elements[i];
return new List2<Integer>( array2, 0, elements.length );
public static List2<Character> create( char... elements ) {
Character[] array2 = new Character[ elements.length * 11 / 10 + 1 ];
for( int i=0; i < elements.length; i++ )
array2[i] = elements[i];
return new List2<Character>( array2, 0, elements.length );
public static List2<Character> create( String s ) {
return create( s.toCharArray() );
public List2<T> clone() {
return new List2<T>( this );
// basic
public int size() {
return size;
private int index( int index ) {
int i = start + index;
if( i >= array.length )
i -= array.length;
return i;
public T get( int d ) {
if( d < 0 || d >= size )
throw new IndexOutOfBoundsException();
if( size == 0 )
throw new NoSuchElementException();
return array[ index( d ) ];
public T set( int index, T element ) {
if( index < 0 || index >= size )
throw new IndexOutOfBoundsException();
int i = index( index );
T oldElement = array[i];
array[i] = element;
return oldElement;
@SuppressWarnings("unchecked")
private void copyAndSetToNewArray( int newArrayLength ) {
T[] newArray = (T[]) new Object[ newArrayLength ];
for( int i=0; i<size; i++ )
newArray[i] = array[ index( i ) ];
init( newArray, 0, size );
public void addFirst( T element ) {
if( size == array.length )
copyAndSetToNewArray( size * 3 / 2 + 1 );
int i = index( array.length - 1 );
array[ i ] = element;
start = i;
size++;
public void addLast( T element ) {
if( size == array.length )
copyAndSetToNewArray( size * 3 / 2 + 1 );
array[ index( size ) ] = element;
size++;
public T removeFirst() {
if( size == 0 )
throw new NoSuchElementException();
T oldElement = array[ start ];
array[ start ] = null;
start = index( 1 );
size--;
if( array.length > size * 2 + 1 )
copyAndSetToNewArray( size * 11 / 10 + 1 );
return oldElement;
public T removeLast() {
if( size == 0 )
throw new NoSuchElementException();
int i = index( size - 1 );
T oldElement = array[i];
array[i] = null;
size--;
if( array.length > size * 2 + 1 )
copyAndSetToNewArray( size * 11 / 10 + 1 );
return oldElement;
@SuppressWarnings("unchecked")
public int removeAll( ListCondition<T> condition ) {
T[] newArray = (T[]) new Object[ array.length ];
int iNew = 0;
for( int i=0; i < size; i++ ) {
T element = get( i );
if( ! condition.isConditionSatisfied( this, i, element ) )
newArray[ iNew++ ] = element;
int oldSize = size;
init( newArray, 0, iNew );
if( array.length > size * 2 + 1 )
copyAndSetToNewArray( size * 11 / 10 + 1 );
return size - oldSize;
// aux
public boolean equals(Object obj) {
if( obj == this )
return true;
if( obj instanceof List2 ) {
List2 that = (List2) obj;
if( this.size != that.size )
return false;
for( int i=0; i < size; i++ )
if( ! Tools.equals( this.array[ this.index(i) ], that.array[ that.index(i) ] ) )
return false;
return true;
if( obj instanceof List ) {
List that = (List) obj;
if( this.size != that.size() )
return false;
Iterator thatIter = that.iterator();
for( int i=0; i < size; i++ )
if( ! Tools.equals( this.array[ this.index(i) ], thatIter.next() ) )
return false;
return true;
return true;
public int hashCode() {
int hashCode = 1;
for( int i=0; i < size; i++ ) {
T element = array[ index( i ) ];
hashCode = 31*hashCode + ( element==null ? 0 : element.hashCode() );
return hashCode;
public boolean isEmpty() {
return size == 0;
public T getFirst() {
return get( 0 );
public T getLast() {
return get( size() - 1 );
public T getRandom() {
return get( (int) (Math.random() * size) );
public int indexOf( Object element ) {
for( int i=0; i < size; i++ )
if( Tools.equals( array[ index( i ) ], element ) )
return i;
return -1;
public int lastIndexOf( Object element ) {
for( int i=size-1; i >= 0; i-- )
if( Tools.equals( array[ index( i ) ], element ) )
return i;
return -1;
public boolean contains( Object element ) {
return indexOf( element ) != -1;
public boolean add( T element ) {
addLast( element );
return true;
@Deprecated
public void add( int index, T element ) {
throw new UnsupportedOperationException();
public T remove() {
return removeFirst();
@Deprecated
public boolean remove( Object element ) {
throw new UnsupportedOperationException( "use removeAll( Condition ) instead" );
@Deprecated
public T remove( int index ) {
throw new UnsupportedOperationException( "use removeAll( Condition ) instead" );
public void clear() {
init();
public Object[] toArray() {
Object[] result = new Object[ size ];
for( int i=0; i < size; i++ )
result[i] = array[ index( i ) ];
return result;
@SuppressWarnings("unchecked")
public <TT> TT[] toArray( TT[] a ) {
if( a.length < size )
a = (TT[]) java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size );
for( int i=0; i < size; i++ )
a[i] = (TT) array[ index( i ) ];
if( a.length > size )
a[size] = null;
return a;
@SuppressWarnings("unchecked")
public void sort() {
Object[] a = toArray();
Arrays.sort( a );
for( int i=0; i < size; i++ )
array[ i ] = (T) a[ i ];
start = 0;
@SuppressWarnings("unchecked")
public void sortDesc() {
Object[] a = toArray();
Arrays.sort( a );
for( int i=0, j=size-1; i < size; i++, j-- )
array[ i ] = (T) a[ j ];
start = 0;
@SuppressWarnings("unchecked")
public void sort( Comparator<T> comparator ) {
T[] a = (T[]) toArray();
Arrays.sort( a, comparator );
for( int i=0; i < size; i++ )
array[ i ] = a[ i ];
start = 0;
@SuppressWarnings("unchecked")
public void sortDesc( Comparator<T> comparator ) {
T[] a = (T[]) toArray();
Arrays.sort( a, comparator );
for( int i=0, j=size-1; i < size; i++, j-- )
array[ i ] = a[ j ];
start = 0;
public String toString( String delimiter ) {
return toString( "", delimiter, "", size() );
public String toString( String prefix, String delimiter, String suffix, int max ) {
StringBuffer stringBuffer = new StringBuffer( prefix );
int dest = Math.min( max, size );
for( int i=0; i < dest; i++ ) {
stringBuffer.append( get(i) );
if( i < dest - 1 )
stringBuffer.append( delimiter );
if( size > max )
stringBuffer.append( "...(" ).append( size() - max ).append( " more)" );
stringBuffer.append( suffix );
return stringBuffer.toString();
// batch operation
public boolean containsAll( Collection<?> that ) {
Set<Object> thisSet = new HashSet<Object>( this );
for( Object element : that )
if( ! thisSet.contains( element ) )
return false;
return true;
@SuppressWarnings("unchecked")
public List2<T> subList( int fromIndex, int toIndex ) {
if( fromIndex < 0 || toIndex > size || toIndex < fromIndex )
throw new IndexOutOfBoundsException();
int newSize = toIndex - fromIndex;
T[] newArray = (T[]) new Object[ newSize * 11 / 10 + 1 ];
for( int i=fromIndex, iNew=0; i < toIndex; i++, iNew++ )
newArray[ iNew ] = array[ index( i ) ];
return new List2<T>( newArray, 0, newSize );
public void addV( T... that ) {
for( T element : that )
addLast( element );
public boolean addAll( Collection<? extends T> that ) {
for( T element : that )
addLast( element );
return ! that.isEmpty();
@Deprecated
public boolean addAll( int index, Collection<? extends T> c ) {
throw new UnsupportedOperationException();
public void removeRest( T element ) {
int position = lastIndexOf( element );
if( position == -1 )
return;
while( ! Tools.equals( element, removeLast() ) );
public void removeAllEquals( final T element ) {
removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T currentElement) {
return currentElement.equals( element );
public void removeAllBetween( final T from, final T to ) {
removeAll( new ListCondition<T>() {
@SuppressWarnings("unchecked")
public boolean isConditionSatisfied(List2 list, int index, T element) {
if( from != null && ((Comparable) from).compareTo( element ) > 0 )
return false;
if( to != null && ((Comparable) to).compareTo( element ) <= 0 )
return false;
return true;
public boolean retainAll( Collection<?> that ) {
final Set<Object> thatSet = new HashSet<Object>( that );
int removeCount = removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T element) {
return ! thatSet.contains( element );
return removeCount > 0;
public boolean removeAll( Collection<?> that ) {
final Set<Object> thatSet = new HashSet<Object>( that );
int removeCount = removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T element) {
return thatSet.contains( element );
return removeCount > 0;
// unit test
private static int maxTestCount = 1000 * 1000;
public static void unitTest() throws Exception {
// thest thoese methods for one time
Tools.ensureEquals( new List2(), new ArrayList() );
Tools.ensureNotEquals( List2.create( "abcde" ), new ArrayList() );
Tools.ensureNotEquals( List2.create( "abcde" ), List2.create( "abcdef" ) );
final List<Double> list1 = new ArrayList<Double>();
final List2<Double> list2 = new List2<Double>();
Runnable[] tasks = new Runnable[] {
// test those methods that do NOT change the list
new Runnable() { public void run() {
Tools.ensureEquals( new List2<Double>( list1 ), list1 );
Tools.ensureEquals( List2.createV( list1.toArray() ), list1 );
Tools.ensureEquals( List2.createV( list1.toArray( new Double[0] ) ), list1 );
double[] doubles = new double[ list1.size() ];
int i = 0;
for( double d : list1 )
doubles[i++] = d;
Tools.ensureEquals( List2.create( doubles ), list1 );
Tools.ensure( list1.isEmpty() == list2.isEmpty() );
Arrays.equals( list1.toArray(), list2.toArray() );
Tools.ensureEquals( list1, list2.clone() );
Double notExistElement = -2.0;
Tools.ensure( list1.indexOf( notExistElement ) == -1 );
Tools.ensure( list1.lastIndexOf( notExistElement ) == -1 );
Tools.ensure( list1.contains( notExistElement ) == false );
Tools.ensureEquals( list1.toString(), list2.toString() );
Tools.ensureEquals( list1.toString(), list2.toString() );
Tools.ensureEquals( list1.hashCode(), list2.hashCode() );
if( list1.isEmpty() )
return;
Tools.ensure( list1.get(0).equals( list2.getFirst() ) );
Tools.ensure( list1.get(list1.size()-1).equals( list2.getLast() ) );
Double existRandomElement = list2.getRandom();
Tools.ensure( list1.contains( existRandomElement ) );
Tools.ensure( list2.contains( existRandomElement ) );
Tools.ensure( list1.indexOf( existRandomElement ) == list2.indexOf( existRandomElement ) );
Tools.ensure( list1.indexOf( existRandomElement ) == list2.indexOf( existRandomElement ) );
int from = (int) (Math.random() * list1.size());
int to = (int) (Math.random() * (list1.size()+1));
if( from > to ) {
int t = from;
from = to;
to = t;
Tools.ensureEquals( list1.subList( from, to ), list2.subList( from, to ) );
// test those methods that change the list
new Runnable() { public void run() {
if( list1.isEmpty() )
return;
int i = (int) (Math.random() * list1.size());
double d = Math.random();
list1.set( i, d );
list2.set( i, d );
new Runnable() { public void run() {
if( list1.isEmpty() )
return;
int i = (int) (Math.random() * list1.size());
Tools.ensure( list1.get( i ).equals( list2.get( i ) ) );
new Runnable() { public void run() {
double d = Math.random();
list1.add( 0, d );
list2.addFirst( d );
new Runnable() { public void run() {
double d = Math.random();
list1.add( d );
list2.addLast( d );
new Runnable() { public void run() {
double d = Math.random();
list1.add( d );
list2.addLast( d );
new Runnable() { public void run() {
if( list1.isEmpty() )
return;
Tools.ensure( list1.remove( 0 ).equals( list2.removeFirst() ) );
new Runnable() { public void run() {
if( list1.isEmpty() )
return;
Tools.ensure( list1.remove( list1.size() - 1 ).equals( list2.removeLast() ) );
new Runnable() { public void run() {
if( list1.isEmpty() )
return;
int i = 0;
for( Iterator<Double> iter=list1.iterator(); iter.hasNext(); i++ ) {
iter.next();
if( i % 3 == 0 )
iter.remove();
list2.removeAll( new ListCondition<Double>() { public boolean isConditionSatisfied(List2 list, int index, Double element) {
return index % 3 == 0;
new Runnable() { public void run() {
double d = Math.random();
list1.add( d );
list2.add( d );
new Runnable() { public void run() {
if( list1.isEmpty() )
return;
Tools.ensure( list1.remove(0).equals( list2.remove() ) );
new Runnable() { public void run() {
if( list1.isEmpty() )
return;
int r = (int) (Math.random() * list1.size());
Double element = list1.get( r );
int index = list1.lastIndexOf( element );
for( int i=list1.size()-1; i>=index; i-- )
list1.remove( i );
list2.removeRest( element );
new Runnable() { public void run() {
list2.removeRest( Math.random() - 2 );
new Runnable() { public void run() {
list1.clear();
list2.clear();
new Runnable() { public void run() {
Collections.sort( list1 );
list2.sort();
new Runnable() { public void run() {
Collections.sort( list1 );
Collections.reverse( list1 );
list2.sortDesc();
new Runnable() { public void run() {
Comparator<Double> comparator = new Comparator<Double>() { public int compare(Double o1, Double o2) {
return o1.toString().substring(2).compareTo( o2.toString().substring(2) );
Collections.sort( list1, comparator );
list2.sort( comparator );
new Runnable() { public void run() {
Comparator<Double> comparator = new Comparator<Double>() { public int compare(Double o1, Double o2) {
return o1.toString().substring(2).compareTo( o2.toString().substring(2) );
Collections.sort( list1, comparator );
Collections.reverse( list1 );
list2.sortDesc( comparator );
new Runnable() { public void run() {
Double notExistElement = -2.0;
list2.removeAllEquals( notExistElement );
Tools.ensureEquals( list1, list2 );
list2.removeAllBetween( 0.5, 0.6 );
for( Iterator<Double> iter=list1.iterator(); iter.hasNext(); ) {
double d = iter.next();
if( d >= 0.5 && d < 0.6 )
iter.remove();
Tools.ensureEquals( list1, list2 );
System.out.print( "test List2 " );
for( int i=0; i < maxTestCount; i++ ) {
tasks[ (int) (Math.random() * tasks.length) ].run();
Tools.ensureEquals( list1, list2 );
if( i % (maxTestCount/10) == 0 )
System.out.print( "." );
System.out.println( " ok" );
// source code : ListCondition
public interface ListCondition<T> {
boolean isConditionSatisfied( List2 list, int index, T element );Hi,
I have the following statement:
private List list = new ArrayList();
why not use private ArrayList list = new
ArrayList()?
I know ArrayList implements List, so list has a wide
scope, right? What's the benefit?
Thanks,
JieBy using the interface you are not tied to a specific implementation.
Later, you may determine that using a LinkedList is more efficient to your specific code and then all you need to do is change the statement to:
private List list = new LinkedList();As long as you are not casting the list reference to ArrayList (or something along those lines) you would not need to change anything else. -
How to read XI Data type in Java code and populate as array list, using UDF
Hi,
How to read XI Data type in Java code and populate as array list, using UDF?
Is there any API using which the XI data types can be read?
Kindly reply.
RichaInput Structure:
<?xml version="1.0" encoding="UTF-8"?>
<ns0:CustomerCreateResp xmlns:ns0="urn:bp:xi:up:re:cust_mdm:cmdm:pr5:100">
<CUSTOMER>
<item>
<CUSTOMERNO/>
<MDMCUSTOMER/>
<CREATE_DATE/>
<RETURN>
<TYPE/>
<MESSAGE/>
</RETURN>
<PT_CONTPART_RETURN>
<item>
<MDM_CONTACT/>
<CONTACT/>
</item>
</PT_CONTPART_RETURN>
<PARTNERS>
<item>
<CUSTOMERNO/>
<PARTNER_FUNCTION/>
<PARTNER_NUMBER/>
<DEFAULT_PARTNER/>
</item>
</PARTNERS>
</item>
</CUSTOMER>
</ns0:CustomerCreateResp>
Output structure
(Sample output structure.This actually needs to be mapped and generated using UDF)
<?xml version="1.0" encoding="UTF-8"?>
<ns1:updateCustomer xmlns:ns1="urn:xiSericeVi"><ns1:customer><ns2:ArrayList xmlns:ns2="java:sap/standard">[]</ns2:ArrayList></ns1:customer><ns1:name>2344566</ns1:name></ns1:updateCustomer> -
Sort array list and using comparable
With the following code I would like to setup a score object for the current player.
Change it to a string(Is it correct to say parse it to a string type)
Then add it to the arraylist.
So I can sort the array list according to the string size.
That's why I have the variables in that order.
So if 3 players have the same amount of guesses, they can be positioned on the high score list according to their gameTime.
//create score object
Score currentScore = new Score(guessCount, gameTime, name);
String currentScoreToString = currentScore.toString();
//add score to arrayList
scores.add(currentScoreToString);So the error message says " The method add(Score) in the type arrayList <Score> is not applicable for the arguments(string)"
Now, I understand that, I would like to know if there is another way to achieve what I am trying to do.
Is the string idea I am trying here possible? is it practical or should I use comparable?
I have looked at comparable, but I don't get it.
Will my Score class implement comparable. I am looking at an example with the following code.
Employee.java
public class Employee implements Comparable {
int EmpID;
String Ename;
double Sal;
static int i;
public Employee() {
EmpID = i++;
Ename = "dont know";
Sal = 0.0;
public Employee(String ename, double sal) {
EmpID = i++;
Ename = ename;
Sal = sal;
public String toString() {
return "EmpID " + EmpID + "\n" + "Ename " + Ename + "\n" + "Sal" + Sal;
public int compareTo(Object o1) {
if (this.Sal == ((Employee) o1).Sal)
return 0;
else if ((this.Sal) > ((Employee) o1).Sal)
return 1;
else
return -1;
ComparableDemo.java
import java.util.*;
public class ComparableDemo{
public static void main(String[] args) {
List ts1 = new ArrayList();
ts1.add(new Employee ("Tom",40000.00));
ts1.add(new Employee ("Harry",20000.00));
ts1.add(new Employee ("Maggie",50000.00));
ts1.add(new Employee ("Chris",70000.00));
Collections.sort(ts1);
Iterator itr = ts1.iterator();
while(itr.hasNext()){
Object element = itr.next();
System.out.println(element + "\n");
}The thing I don't understand is why it returns 0, 1 or -1(does it have to do with the positioning according to the object is being compared with?)
What if I only use currentScore in a loop which loops every time the player restarts?
//create score object
Score currentScore = new Score(guessCount, gameTime, name);
String currentScoreToString = currentScore.toString();
//add score to arrayList
scores.add(currentScoreToString);Also why there is a method compareTo, and where is it used?
Thanks in advance.
Edited by: Implode on Oct 7, 2009 9:27 AM
Edited by: Implode on Oct 7, 2009 9:28 AMjverd wrote:
Implode wrote:
I have to hand in an assignment by Friday, and all I have to do still is write a method to sort the array list. Okay, if you have to write your own sort method, then the links I provided may not be that useful. They show you how to use the sort methods provided by the core API. You COULD still implement Comparable or Comparator. It would just be your sort routine calling it rather than the built-in ones.
You have two main tasks: 1) Write a method that determines which of a pair of items is "less than" the other, and 2) Figure out a procedure for sorting a list of items.
The basic idea is this: When you sort, you compare pairs of items, and swap them if they're out of order. The two main parts of sorting are: 1) The rules for determining which item is "less than" another and 2) Determining which pairs of items to compare. When you implement Comparable or create a Comparator, you're doing #1--defining the rules for what makes one object of your class "less than" another. Collections.sort() and other methods in the core API will call your compare() or compareTo() method on pairs of objects to produce a sorted list.
For instance, if you have a PersonName class that consists of firstName and lastName, then your rules might be, "Compare last names. If they're different, then whichever lastName is less indicates which PersonName object is less. If they're the same, then compare firstNames." This is exactly what we do in many real-life situations. And of course the "compare lastName" and "compare firstName" steps have their own rules, which are implemented by String's compareTo method, and which basically say, "compare char by char until there's a difference or one string runs out of chars."
Completely independent of the rules for comparing two items is the algorithm for which items get compared and possibly swapped. So, if you have 10 Whatsits (W1 through W10) in a row, and you're asked to sort them, you might do something like this:
Compare the current W1 to each of W2 through W10 (call the current one being compared Wn). If any of them are less than W1, swap that Wn with W1 and continue on, comparing the new W1 to W(n+1) (that is, swap them, and then compare the new first item to the next one after where you just swapped.)
Once we reach the end of the list, the item in position 1 is the "smallest".
Now repeat the process, comparing W2 to W3 through W10, then W3 to W4 through W10, etc. After N steps, the first N positions have the correct Whatsit.
Do you see how the comparison rules are totally independent of the algorithm we use to determine which items to compare? You can define one set of comparison rules ("which item is less?") for Whatsits, another for Strings, another for Integers, and use the same sorting algorithm on any of those types of items, as long as you use the appropriate comparison rules.Thanks ;)
massive help
I understand that now, but I am clueless on how to implement it.
Edited by: Implode on Oct 7, 2009 10:56 AM -
Hi,
I have an array List which have values like empid, amount, corpcode eg.
223, 345.95, SDB
791, 567.75, XYZ
115, 345.95, SDB
I need to sort this array like this
115, 345.95, SDB
223, 345.95, SDB
791, 567.75, XYZ
How can I do this?
ThanksYou have to implement a natural order for your object, so that it can be sorted. There are a lot of tutorials out there for this, but I will do it anyway for you:
public YourClass implements Comparable<YourClass>{
int firstNumber;
int secondNumber;
int thirdNumber;
String someIdentifier;
public int compareTo(YourClass otherObject){
int difference = this.firstNumber - otherObject.firstNumber;
if(difference != 0) return difference;
difference = this.secondNumber - otherObject.secondNumber;
if(difference != 0) return difference;
return this.someIdentifier.compareTo(otherObject.someIdentifier);
}As you can see, the basic idea is, that you return if an object is greater, equal or less than another. You begin with the most important criteria. If this one is equal, you check the next one.
Some objects already include the comparable interface, like String. If this is the case, you can take advantage of this, and use their compareTo Method.
After this, you can sort your objects with
Collections.sort(someList); -
Returning a Tcl list to TestStand
Hi,
I wonder if anyone can help me. I would like to return the contents of a Tcl list to TestStand. I am not sure how to go about it. Are Tcl lists equivalent to an array in TestStand? Can I return the entire list or must I return each individual element? I also noticed that the custom TclParameter type can be modified. Should I create an array of strings to catch the list being returned from Tcl.
Any help would be appreciated.
ThanksA Tcl list is very similar to an array in TestStand. There are some minor differences when dealing with multi-dimensional lists (lists of lists), but the concept is pretty similar. The Tcl Example currently on the web does not support lists and all parameters must be strings. You would then have to parse the string returned as the list in order to make an array.
For example, if you have a Tcl list x created with": set x [1 2 3 4]". If you set an output parameter on the step to map to the variable x to Locals.ListAsString in TestStand, it would be populated with "1 2 3 4". You would have to then split the string based on spaces, and you could convert it into an Array in TestStand.
Do not modify the TclParameter type (unless you also want to change the source code of the rest of the step). Changing the source code for the step type would be an advanced topic, so unless you are experienced in TestStand and the Tcl C API, I wouldn't recommend it.
Allen P.
NI -
Trying to fetch a value in a java function and returning the array.
hello....I am trying to fetch a value in a java function and returning a array......I already write the pl/sql function which is working fine....but i think i m lost......when i run it through the jsp it shows me error........pls help
java code:=
public String [] viewx(String bid) throws SQLException, Exception {
String [] values;
try {
CallableStatement cstmt = null;
String SQL = "{?=call vi_dis.v_dis(?)}";
cstmt = con.prepareCall(SQL);
cstmt.registerOutParameter(1,Types.ARRAY);
cstmt.setString(2, bid);
cstmt.execute();
Array simpleArray = cstmt.getArray(1);
values = (String [])simpleArray.getArray();
cstmt.close();
} catch (SQLException sqle) {
error = "SQLException: Could not execute the query.";
throw new SQLException(error);
} catch (Exception e) {
error = "An exception occured while retrieving emp.";
throw new Exception(error);
return values;
pl/sql function
create or replace package vi_dis
as
function v_dis(vbid IN student.bid%type) return stuarray ;
end;
create or replace
package body vi_dis
as
function v_dis(vbid IN student.bid%type) return stuarray
is
l_stu stUarray :=stuarray();
cursor c_sel
is
SELECT CNAME
FROM COURSE C,ENROLL E
WHERE C.CID=E.CID
AND E.BID=vbid;
BEGIN
OPEN c_sel;
FETCH c_sel BULK COLLECT INTO l_stu;
l_stu.extend;
CLOSE c_sel;
RETURN l_stu;
EXCEPTION
WHEN NO_DATA_FOUND
THEN DBMS_OUTPUT.PUT_LINE('NO RESULT AVAILABLE');
CLOSE c_sel;
END;
END;
/BalusC wrote:
It is comparing the selected value against the List<SelectItem> returned by getSetoresOrigem() as it is during the apply request values phase of the form submit request.Ok. That's what I supposed JSF was doing.
BalusC wrote:
If the selected value isn't in there, then you will get this error.I can understand this, but is this right? As I said, the old value isn't really there because I changed the list values to new ones. But the new value (the value of fSetorOrigem ) corresponds to a value that exist in the new list items, so a valid value. So JSF is not considering that I also changed the list, not just the value. It is comparing the new value with the old list, not the new one. Acting like this JSF is making the page looks like a static HTML page, not a dynamic one. If I can't change the list and the value, what's the point of that? In my point of view I'm not doing anything wrong, I'm not violating any JSF rules.
Marcos
Maybe you are looking for
-
Final Cut Studio 2(Color) and AGP graphics cards
So I have ordered FCS 2 for my business(Videography with HDV cameras). I am on the 2.0 Ghz G5 with dual processors and a 23' Apple Cinema Display. The computer came with the ATI 9600 Pro Radeon card. All the technical requirements for Color are PCI s
-
Custom code life cycle management (CCLM)
Hi Gurus , At this moment i'm working on Custom code life cycle management concept in Solution Manager. If any one worked on this one previously can you please send me complete document. It's Urgent Plssssss Thanks in Advance... Vijay R.
-
Script to archive File Server Data
Hi All, I'm looking for a script to remove the file server data by keeping last 2 years? As
-
Win 2008R2 terminal services, it won't show Windows 8.1 pro redirected printer
I have users that use a remote app on a Win2008R2 server. Redirected printers work fine on Windows 7, but I cannot get it to display the redirected printer attached to a Windows 8.1 client. I have installed the printer driver on the server as usual.
-
Transport Gateway HTTP versus Email
Which mode is generally preferred for the Transport Gateway: HTTP or email? Are there advantages to using one mode over the other? I seem to remember talking with someone from Cisco about this and remember that they had some good arguments for which