Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
yatagan
Aug 31, 2009

by Ozma

Otto Skorzeny posted:

Oh hurr mental parse failure

Also, does java support \W as the class of non-word characters or is that a perlism that hasn't caught on in javaland

For 1.6 it's working: "testing split".split("\\W"). Here's what I would use to parse your special stuff, bet it'll get just about everything:

myString.split("[^\\w'-]");

Adbot
ADBOT LOVES YOU

ToastedZergling
Jun 25, 2007

Chubby Walrus:
The Essence of Roundness
Thanks guys. I think I'm just going to have to roll my own "grammar," string parser, or whatever you want to call it. Time to convert javascript into java.

If I steal your code I'll leave you in a comment "GOON GRAMMAR IS THE GREATEST"

Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip

ToastedZergling posted:

Thanks guys. I think I'm just going to have to roll my own "grammar," string parser, or whatever you want to call it. Time to convert javascript into java.

If I steal your code I'll leave you in a comment "GOON GRAMMAR IS THE GREATEST"

A grammar is something separate from regular expressions, although they use some similar concepts.

For an example, see the right sidebar on http://json.org , which contains the grammar describing JSON.

Max Facetime
Apr 18, 2009

ToastedZergling posted:

tldr; I prefer leveraging existing frameworks than writing custom parsing

I doubt there's such a thing, here are a couple of reasons:

Yahoo! Mail: The best web-based email!

.NET Rocks! - My .NET Story

E*TRADE del.icio.us Mercedes-Benz

Fake edit: good luck :)

ToastedZergling
Jun 25, 2007

Chubby Walrus:
The Essence of Roundness

I am in posted:

I doubt there's such a thing, here are a couple of reasons:

Yahoo! Mail: The best web-based email!

.NET Rocks! - My .NET Story

E*TRADE del.icio.us Mercedes-Benz

Fake edit: good luck :)

*cries* These are some great edge cases to think about.

But it's a good thing we're dealing with medical terms and not too many wacky brand names.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

fletcher posted:

Why does this work fine the first time, but subsequent calls give me the "you must be a registered user to view this page..."

code:
public static String fetchPage(String urlString) {
	StringBuilder page = new StringBuilder();
	try {
		URL url = new URL(urlString);
		URLConnection conn = url.openConnection();
		conn.setRequestProperty("Cookie", "bbuserid=38563; bbpassword=editedout");
		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String line;
		while ((line = reader.readLine()) != null) {
			page.append(line);
		}
		reader.close();
	} catch (MalformedURLException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return page.toString();
}

String page = SomethingAwful.fetchPage("http://forums.somethingawful.com/member.php?action=getinfo&userid=38563");
			
String page2 = SomethingAwful.fetchPage("http://forums.somethingawful.com/member.php?action=getinfo&userid=38563");

Bump! This is driving me nuts!

LakeMalcom
Jul 3, 2000

It's raining on prom night.

fletcher posted:

Bump! This is driving me nuts!

Can't answer your actual question, but I wrote a scraper-type thing using WebDriver:

http://code.google.com/p/selenium/wiki/GettingStarted

Max Facetime
Apr 18, 2009

fletcher posted:

Bump! This is driving me nuts!

I looked at the cookie that is sent with Firebug. These keys have values: sessionid, __utma, aduserid, bbuserid, bbpassword and sessionhash.

Try to catch them all from your browser and see if it works. It's hard to say why it works the first time without knowing the internals of the forums software.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

I am in posted:

I looked at the cookie that is sent with Firebug. These keys have values: sessionid, __utma, aduserid, bbuserid, bbpassword and sessionhash.

Try to catch them all from your browser and see if it works. It's hard to say why it works the first time without knowing the internals of the forums software.

I was doing it before in PHP with just the bbuserid and bbpassword so I don't think that's the issue. I'm trying to do this on Google App Engine now.

fletcher fucked around with this message at 00:11 on Mar 17, 2010

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
I'm trying to run a program (.exe) from inside Java, and read its results, but Java is getting completely different results from cmd.exe. cmd.exe gets the correct results.

The program takes in a string and an int and hashes the first X characters.
Using cmd:
Z:\>hashlittle.exe a 1
58d68708

Java gets "8ba9414b" instead. Help?
code:
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class minrun {

	public static void main(String args[]) {
		Runtime r = Runtime.getRuntime();
		Process p = null;
		try {
			String s = "Z:\\hashlittle.exe a 1";
			p = r.exec(s);
			BufferedReader input =
				new BufferedReader
				(new InputStreamReader(p.getInputStream()));
			String line = input.readLine();
			System.out.println(line);
		} catch(Exception e) {
			System.out.println("e");
		}
	}
}
Also,
Z:\>hashlittle.exe a 0
deadbeef
Java gets "31b8a510".

Edit: It works now. I don't know where or how I fixed it. :suicide:
Oh, except that I'm using a different compilation of the hashlittle file.
Z:\>hashlittle.exe a 1
58d68708

Z:\>hashlittleB.exe a 1
58d68708

But hashlittleB.exe works in Java and hashlittle.exe doesn't. :byodood:

Malloc Voidstar fucked around with this message at 05:45 on Mar 17, 2010

RitualConfuser
Apr 22, 2008

fletcher posted:

Why does this work fine the first time, but subsequent calls give me the "you must be a registered user to view this page..."

I can't seem to reproduce the issue just invoking that method from a test program.

HFX
Nov 29, 2004

Otto Skorzeny posted:

A grammar is something separate from regular expressions, although they use some similar concepts.

For an example, see the right sidebar on http://json.org , which contains the grammar describing JSON.

Not entirely separate, since one is a subset of the other.

Kaltag
Jul 29, 2003

WHAT HOMIE? I know dis ain't be all of it. How much of dat sweet crude you be holdin' out on me?
Could anyone recommend to me a way to send SMS messages using java? So far I see that I can get a GMS modem or use a web service that java can access, or a java library that uses a web service or hell I don't know. These are things I learned from google, and there are many .jars out there that claim to be the best at sending sms.

HFX
Nov 29, 2004

Kaltag posted:

Could anyone recommend to me a way to send SMS messages using java? So far I see that I can get a GMS modem or use a web service that java can access, or a java library that uses a web service or hell I don't know. These are things I learned from google, and there are many .jars out there that claim to be the best at sending sms.

Most companies have a email drop that works for sending SMS messages. Just send an email to the persons mailbox and it will get sent to their phone. There are other more in depth ways, but that one works surprisingly well.

Surface
May 5, 2007
<3 boomstick

HFX posted:

Most companies have a email drop that works for sending SMS messages. Just send an email to the persons mailbox and it will get sent to their phone. There are other more in depth ways, but that one works surprisingly well.

This is the easiest way to go.

From: http://www.makeuseof.com/tag/email-to-sms/

Free Email To SMS Gateways (Major US Carriers)

Carrier Email to SMS Gateway
Alltel [10-digit phone number]@message.alltel.com
Example: 1234567890@message.alltel.com
AT&T (formerly Cingular) [10-digit phone number]@txt.att.net
[10-digit phone number]@mms.att.net (MMS)
[10-digit phone number]@cingularme.com
Example: 1234567890@txt.att.net
Boost Mobile [10-digit phone number]@myboostmobile.com
Example: 1234567890@myboostmobile.com
Nextel (now Sprint Nextel) [10-digit telephone number]@messaging.nextel.com
Example: 1234567890@messaging.nextel.com
Sprint PCS (now Sprint Nextel) [10-digit phone number]@messaging.sprintpcs.com
[10-digit phone number]@pm.sprint.com (MMS)
Example: 1234567890@messaging.sprintpcs.com
T-Mobile [10-digit phone number]@tmomail.net
Example: 1234567890@tmomail.net
US Cellular [10-digit phone number]email.uscc.net (SMS)
[10-digit phone number]@mms.uscc.net (MMS)
Example: 1234567890@email.uscc.net
Verizon [10-digit phone number]@vtext.com
[10-digit phone number]@vzwpix.com (MMS)
Example: 1234567890@vtext.com
Virgin Mobile USA [10-digit phone number]@vmobl.com
Example: 1234567890@vmobl.com

Flobbster
Feb 17, 2005

"Cadet Kirk, after the way you cheated on the Kobayashi Maru test I oughta punch you in tha face!"

Surface posted:

Free Email To SMS Gateways (Major US Carriers)

These work with varying levels of success, so I'm not sure if I'd depend on them for anything critical.

I've been generalizing the e-mail notification mechanism on the server I work on to provide different kinds of notifications, like SMS and Twitter. I tested out the e-mail->SMS gateway using my number on AT&T and the messages I sent were either completely lost or arrived 12 hours later.

I think what we're going to end up doing is using some of the sample code out there that sends post requests directly to Google Voice (since it lacks a real API) to send text messages through that. It didn't appear that there was anything in the TOS preventing it.

chippy
Aug 16, 2006

OK I DON'T GET IT
Would something like this be any use to you?

http://www.bulksms.com/

There's a few companies that do this sort of thing, this one has various methods for sending the texts including an actual API.

Flamadiddle
May 9, 2004

chippy posted:

Would something like this be any use to you?

http://www.bulksms.com/

There's a few companies that do this sort of thing, this one has various methods for sending the texts including an actual API.

We use these guys at work. They're very good, but their API doesn't quite do everything we need so we've had to cut some corners.

LT.CrownRoast
Mar 20, 2009

by XyloJW
I'd like to get better with Tomcat in general and am looking for a few webapps that I could configure as part of the process, to spark more interest.

Things like, cacti/mtrg, streaming audio/video, or xbmc/file sharing (Note: These are just guidelines so don't necessarily take them literally.) Something for the experience of setting it up and getting it running without getting bored to tears along the way.

Kaltag
Jul 29, 2003

WHAT HOMIE? I know dis ain't be all of it. How much of dat sweet crude you be holdin' out on me?
I don't want to have to know what carriers my targets are using. I also don't want to use anything "free" lest my customers get loving ads or end up on a mailing list. Also, security is an issue.

I actually found http://www.message-media.com/ and they had a fairly simple api I was able to import to eclipse and I talked to their sales people and got 50 free texts to test with. I guess later you end up buying bulk once your poo poo hits mainstream.

As the program I am working on gets more serious we'll probably just start integrating a gsm modem and proper provider.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Is there a way to check and see if anything has been written to a HttpServletResponse?

Max Facetime
Apr 18, 2009

fletcher posted:

Is there a way to check and see if anything has been written to a HttpServletResponse?

isCommintted() may be what you're looking for in ServletResponse.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

I am in posted:

isCommintted() may be what you're looking for in ServletResponse.

Sounded promising but didn't work quite the way I wanted. I've got the main entry point to my webapp which does my user authentication and then it hands it off to another controller based on the request. If it gets back to my main servlet and nothing has been written using to getOutputStream().write() yet I want to print out some sort of error page.

code:
response.setContentType("text/html; charset=UTF-8");
response.getOutputStream().write(template.toString().getBytes("utf-8"));
System.out.println(response.isCommitted());
Prints out false

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

fletcher posted:

Sounded promising but didn't work quite the way I wanted. I've got the main entry point to my webapp which does my user authentication and then it hands it off to another controller based on the request. If it gets back to my main servlet and nothing has been written using to getOutputStream().write() yet I want to print out some sort of error page.

code:
response.setContentType("text/html; charset=UTF-8");
response.getOutputStream().write(template.toString().getBytes("utf-8"));
System.out.println(response.isCommitted());
Prints out false

You can wrap HttpServletResponse with your own implementation that will facade the setters and outputstream so you can detect if data has been sent to the class.

Max Facetime
Apr 18, 2009

You could wrap the original HttpServletResponse like this:

code:
class MyResponse extends HttpServletResponseWrapper
then return a similarly wrapped OutputStream from getOutputStream(), but consider do you really want to do this instead of catching an exception or an error code? The thing about isCommitted() is that you can rewind a partially rendered response and render an error page instead.

E: beaten!

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

I am in posted:

You could wrap the original HttpServletResponse like this:

code:
class MyResponse extends HttpServletResponseWrapper
then return a similarly wrapped OutputStream from getOutputStream(), but consider do you really want to do this instead of catching an exception or an error code? The thing about isCommitted() is that you can rewind a partially rendered response and render an error page instead.

E: beaten!

drat! That was kinda what I had originally done but I thought I was doing it wrong so I got rid of it.

Is it common to extend HttpServletRequestWrapper and HttpServletResponseWrapper? It seems like it might be convenient to put information about the logged in user and stuff in a custom request object since I pass the request/response objects around to so many methods.

Basically how I have it setup now is:

Request hits MainServlet.java with url like http://site.com/articles/today
-MainServlet.java does everything in a try/catch, logs/emails me on exceptions. Displays friendly error page to user on exception, 99% of the time exceptions will be handled in the other controllers with more specific error message
-authenticate user if credentials supplied
-parse URL to figure out what controller to instantiate (articles = ArticleController.java)
-call doGet or doPost in ArticleController.java, writes to response.getOutputStream()
-now i'm back in MainServlet.java, 99% of the time a response should already be written. want to avoid a blank page if one hasn't been written yet though

fletcher fucked around with this message at 20:01 on Mar 26, 2010

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

fletcher posted:

drat! That was kinda what I had originally done but I thought I was doing it wrong so I got rid of it.

Is it common to extend HttpServletRequestWrapper and HttpServletResponseWrapper? It seems like it might be convenient to put information about the logged in user and stuff in a custom request object since I pass the request/response objects around to so many methods.

Basically how I have it setup now is:

Request hits MainServlet.java with url like http://site.com/articles/today
-MainServlet.java does everything in a try/catch, logs/emails me on exceptions. Displays friendly error page to user on exception, 99% of the time exceptions will be handled in the other controllers with more specific error message
-authenticate user if credentials supplied
-parse URL to figure out what controller to instantiate (articles = ArticleController.java)
-call doGet or doPost in ArticleController.java, writes to response.getOutputStream()
-now i'm back in MainServlet.java, 99% of the time a response should already be written. want to avoid a blank page if one hasn't been written yet though

You know you can map error responses to servlet actions via the error-page declarations in your web.xml?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

TRex EaterofCars posted:

You know you can map error responses to servlet actions via the error-page declarations in your web.xml?

I did not! That sounds like what I need to be doing. Am I supposed to have more than 1 servlet defined in web.xml with url-patterns to map things like /articles to ArticleController.java?

And if I use the error-page stuff, do I not need to be doing everything in 1 main try/catch?

fletcher fucked around with this message at 21:00 on Mar 26, 2010

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

fletcher posted:

I did not! That sounds like what I need to be doing. Am I supposed to have more than 1 servlet defined in web.xml with url-patterns to map things like /articles to ArticleController.java?

And if I use the error-page stuff, do I not need to be doing everything in 1 main try/catch?

You can do pretty much anything you want, but it would be best to have a servlet to handle errors separate from the servlets that handle regular traffic. Map the error handling to the error servlet and write your logging/emailing code there so you don't pollute your main servlet with poo poo.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

TRex EaterofCars posted:

You can do pretty much anything you want, but it would be best to have a servlet to handle errors separate from the servlets that handle regular traffic. Map the error handling to the error servlet and write your logging/emailing code there so you don't pollute your main servlet with poo poo.

Something like this?

web.xml
code:
<servlet>
	<servlet-name>MainServlet</servlet-name>
	<servlet-class>com.project.MainServlet</servlet-class>
</servlet>

<servlet>
	<servlet-name>ErrorServlet</servlet-name>
	<servlet-class>com.project.ErrorServlet</servlet-class>
</servlet>

<servlet-mapping>
	<servlet-name>ErrorServlet</servlet-name>
	<url-pattern>/error</url-pattern>
</servlet-mapping>

<servlet-mapping>
	<servlet-name>MainServlet</servlet-name>
	<url-pattern>/</url-pattern>
</servlet-mapping>

<error-page>
	<exception-type>com.project.TestException</exception-type>
	<location>/error</location>
</error-page>
Once I'm in the ErrorServlet, how do I find out more information about the exception that led me there?

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
I came across something rather odd that I couldn't figure out-

code:
Arrays.asList(new char[] {'a','b'}).contains('a');
Arrays.asList(new String[] {"a","b"}).contains("a");
The first line evaluates to false, and the second evaluates to true. In the first case, I'd assumed that the character literal 'a' would be autoboxed as a Character (since the List.contains() method takes an object) and the elements of the char array would similarly autobox, so they will then be compared via their respective equals() methods. This doesn't appear to be the case, as this:

code:
Arrays.asList(new Character[] {'a', 'b'}).contains('a');
which will force that second autobox, evaluates to true as expected.

Any thoughts? What am I missing here?

Flobbster
Feb 17, 2005

"Cadet Kirk, after the way you cheated on the Kobayashi Maru test I oughta punch you in tha face!"

Internet Janitor posted:

Any thoughts? What am I missing here?

This appears to be a perfect storm of weirdness involving the way Java handles varargs and generics. The signature of Arrays.asList is the following:

code:
public static <T> List<T> asList(T... a)
Since the method takes variable arguments, you can pass them in separately or as an explicit array, as you have done. Inside the method, "a" is just an array of 0 or more elements of type T. By the rules of Java generics, type parameters like T must be reference types, such as an instance of a class or an array, but not a primitive. So, the substitution that you're expecting, where T = char and your array is treated as the varargs array with two char elements, won't work:

code:
public static <char> List<char> asList(char... a) // where a = new char[] { 'a', 'b' } <-- NO
The compiler then tries the next best thing, T = char[], which does work: it treats the whole array as the one and only element of the varargs array:

code:
public static <char[]> List<char[]> asList(char[]... a) // where a = new char[][] { new char[] { 'a', 'b' } } <-- OK
So the list you get back is a List<char[]> that contains one element, which is an array of two characters.

Why doesn't it try T = Character instead? The compiler is choosing the "path of least conversions", so to speak. It's "easier/less effort" to treat the array as the object that it is instead of boxing every element in the array for you. That's why your final example works, because you've explicitly done the boxing for it already:

code:
public static <Character> List<Character> asList(Character... a) // where a = new Character[] { 'a', 'b' } <-- OK
This is just another illustration of one of those wonderful edge cases in Java generics that lead me to detest the way they've implemented them. :suicide:

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."

Flobbster posted:

This is just another illustration of one of those wonderful edge cases in Java generics that lead me to detest the way they've implemented them. :suicide:

I believe I follow you- thanks for the explanation. I hadn't even realized Arrays.asList() took a vararg!

Always better to run into this kind of subtle thing on a personal project than with a production codebase, at any rate...

Necc0
Jun 30, 2005

by exmarx
Broken Cake
I'm just getting into generics in java and I can't figure out how to compare to generic variables.

code:
// Definition of class TreeNode and class Tree.

// class TreeNode definition
class TreeNode< E extends Comparable< E> >
{
   // package access members
   TreeNode leftNode; // left node  
   E data; // node value
   TreeNode rightNode; // right node

   // constructor initializes data and makes this a leaf node
   public TreeNode( Comparable<E> nodeData )
   { 
      data = (E) nodeData;              
      leftNode = rightNode = null; // node has no children
   } // end TreeNode constructor

   // locate insertion point and insert new node; ignore duplicate values
   public void insert( Comparable<E> insertValue )
   {
      // insert in left subtree
      if ( insertValue.compareTo(data))
      {
         // insert new TreeNode
         if ( leftNode == null )
            leftNode = new TreeNode( insertValue );
         else // continue traversing left subtree
            leftNode.insert( insertValue ); 
      } // end if
      else // insert in right subtree
      {
         // insert new TreeNode
         if ( rightNode == null )
            rightNode = new TreeNode( insertValue );
         else // continue traversing right subtree
            rightNode.insert( insertValue ); 
      } // end else if
   } // end method insert
} // end class TreeNode

// class Tree definition
public class Tree< E extends Comparable< E > >
{
   private TreeNode root;

   // constructor initializes an empty Tree of integers
   public Tree() 
   { 
      root = null; 
   } // end Tree no-argument constructor

   // insert a new node in the binary search tree
   public void insertNode( E insertValue )
   {
      if ( root == null )
         root = new TreeNode( insertValue ); // create the root node here
      else
         root.insert( insertValue ); // call the insert method
   } // end method insertNode

   // begin preorder traversal
   public void preorderTraversal()
   { 
      preorderHelper( root ); 
   } // end method preorderTraversal

   // recursive method to perform preorder traversal
   private void preorderHelper( TreeNode node )
   {
      if ( node == null )
         return;

      System.out.printf( "%d ", node.data ); // output node data
      preorderHelper( node.leftNode );       // traverse left subtree
      preorderHelper( node.rightNode );      // traverse right subtree
   } // end method preorderHelper

   // begin inorder traversal
   public void inorderTraversal()
   { 
      inorderHelper( root ); 
   } // end method inorderTraversal

   // recursive method to perform inorder traversal
   private void inorderHelper( TreeNode node )
   {
      if ( node == null )
         return;

      inorderHelper( node.leftNode );        // traverse left subtree
      System.out.printf( "%d ", node.data ); // output node data
      inorderHelper( node.rightNode );       // traverse right subtree
   } // end method inorderHelper

   // begin postorder traversal
   public void postorderTraversal()
   { 
      postorderHelper( root ); 
   } // end method postorderTraversal

   // recursive method to perform postorder traversal
   private void postorderHelper( TreeNode node )
   {
      if ( node == null )
         return;
  
      postorderHelper( node.leftNode );      // traverse left subtree
      postorderHelper( node.rightNode );     // traverse right subtree
      System.out.printf( "%d ", node.data ); // output node data
   } // end method postorderHelper

} // end class Tree
my TreeTest class is trying to create and compare integers, doubles, and strings, but the compiler only makes it to the integers and throws an error saying:
incompatible types
required: boolean
found: int

this is the if statement inside the insert function. help?

Wooper
Oct 16, 2006

Champion draGoon horse slayer. Making Lancers weep for their horsies since 2011. Viva Dickbutt.
The if-statement require a boolean but compareTo return an integer.
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Comparable.html#compareTo%28java.lang.Object%29

Necc0
Jun 30, 2005

by exmarx
Broken Cake
:doh: thanks

Brain Candy
May 18, 2006

Necc0 posted:

I'm just getting into generics in java and I can't figure out how to compare to generic variables.

code:
class TreeNode< E extends Comparable< E> >
{
   ...

   public TreeNode( Comparable<E> nodeData )
   { 
      data = (E) nodeData;              
      leftNode = rightNode = null; // node has no children
   }
...

You can just use E instead of Comparable<E> in your method signature, there is
no need for casting.

code:
class TreeNode< E extends Comparable< E> >
{
   ...

   public TreeNode(E nodeData )
   { 
      data = nodeData;              
      leftNode = rightNode = null; // node has no children
   }
...

karuna
Oct 3, 2006
I'm trying to make a deep copy of a LinkedList<ArrayList<String>>

Doesn't seem to be working for me, I have a feeling it is only creating a swallow copy of the arrayList<String>

I've tried two methods
code:
LinkedList<ArrayList<String>> holdOutDataset = new LinkedList<ArrayList<String>(dataset);

Collections.copy(holdOutDataset, dataset);
and

code:
ListIterator<ArrayList<String>> it = dataset.listIterator();
int k = 0;
while(it.hasNext()){
	    holdOutDataset.add(it.next());
}
Any idea's how I can make a deep copy of the above Linkedlist?

Necc0
Jun 30, 2005

by exmarx
Broken Cake

Brain Candy posted:

You can just use E instead of Comparable<E> in your method signature, there is
no need for casting.

code:
class TreeNode< E extends Comparable< E> >
{
   ...

   public TreeNode(E nodeData )
   { 
      data = nodeData;              
      leftNode = rightNode = null; // node has no children
   }
...

yeah since I'm new to generics I thought my problem had something to do with how I was handling the objects, not the actual logic in the if statement. :downs:

Adbot
ADBOT LOVES YOU

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.

karuna posted:

I'm trying to make a deep copy of a LinkedList<ArrayList<String>>
code:
LinkedList<ArrayList<String>> result = new blah blah blah;
for(ArrayList<String> l : sourceList)
  result.add(new ArrayList<String>(l));

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply