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
Alvie
May 22, 2008

Mr.Radar posted:

Strings are immutable (which means you can't change the value of a String instance), but references to strings (remember in Java that all object variables are really references to object instances or null) are definitely mutable.
Thanks for the explanation. I'm so used to c++ that Java has been a little weird getting used to. It's close enough to make me confident but different enough to really screw with me when I get something wrong.

Somebody once told me there were no pointers in Java. Seems to me like everything is a pointer in Java, it just doesn't go out and say it.

Adbot
ADBOT LOVES YOU

yatagan
Aug 31, 2009

by Ozma

Alvie posted:

Somebody once told me there were no pointers in Java. Seems to me like everything is a pointer in Java, it just doesn't go out and say it.

A pointer is a reference to a memory location, and you Java doesn't do programmer accessible memory. Therefore, because you can never directly access a Java pointer, only the object it references, it's as if pointers don't exist.

zootm
Aug 8, 2006

We used to be better friends.

necrobobsledder posted:

Contiguous memory is the issue - I've seen cases where it won't start with more than 768MB for -Xmx. In a lot of configurations, you won't be able to allocate more than 1.5GB of memory in a single segment for the application. If you need more than 1 GB of memory for your Java app, you should be looking at 64-bit JVMs and OSes as part of a scaling strategy.
Of course you could consider scaling out instead of up with something like Terracotta, which to me looks like black magic.

6174
Dec 4, 2004
I've got a frustrating problem with generics. I have a function prototype I need to conform to:
code:
public static <T> T[] foo(Iterable<T> bar)
The problem I'm having is returning a T[]. Right now I have the correct result sitting in an ArrayList, but every means of converting that I've tried with .toArray() gives me an error of attempting to create a generic array. Is there some way to do this? Or do I have to go try and get this function prototype changed?

1337JiveTurkey
Feb 17, 2005

Do you know the actual type of the array where you're calling it? The Collection.toArray() method takes an array of the type that you want and uses reflection to make a bigger one if it's not large enough.

code:
Collection<String> foo = new ArrayList<String>();
String[] bar = foo.toArray(new String[foo.size()]);
Since Java generics don't retain that information at runtime and arrays need an actual type to construct from, this means that a type needs to be supplied at the time of construction. While the Collection.toArray() method is one example the static method ServiceLoader.load() takes a Class<T> as its argument (usually an interface) and returns a ServiceLoader<T>.

Of course if you can't change it, things get messy. One possibility (haven't tested it but it should work) is to figure out the type based on the elements of the iterator. Keep in mind that this is mostly from memory written in an IDE called 'Firefox'.

code:
// This will be a list of all the possible classes the array can be
List<Class> classes = null;
Class<T> survivor = null;
for (T t : bar) {
  if (classes == null) {
    // Adding the classes on the first pass is the same as removing
    // everything else from the universal set
    classes = Arrays.asList(t.getClass().getClasses())
  }
  else {
    // Rest of the iterations remove classes from the initial one
    classes.retainAll(Arrays.asList(t.getClass().getClasses()));
  }
}
if (classes.size() == 1) {
  survivor = (Class<T>) classes.get(1);
}
else {
  // Now to trim things down a bit by removing the boring ones
  List<Class> remaining = new ArrayList<Class>(classes);
  for (Iterator<Class> it = remaining.iterator(); it.hasNext();) {
    Class candidate = it.getNext()
    for (Class clazz : classes) {
      if (candidate == Object.class ||
          candidate != clazz &&
          candidate.isAssignableFrom(clazz)) {
        it.remove();
        break;
      }
    }
  }
  if (remaining.size == 1) {
    survivor = (Class<T>) remaining.get(0);
  }
  else {
    survivor = (Class<T>) remaining.get(new Random().nextInt(remaining.size));
  }
}
// Use reflection to generate an instance of the actual class
T[] retVal = (T[]) Array.instanceOf(survivor, bar.size());

6174
Dec 4, 2004

1337JiveTurkey posted:

Do you know the actual type of the array where you're calling it?

Yes and no. This interface was specified as part of a homework problem. In the context of the trivial main method sitting in front of this method, I do know the type. However part of the instructions state that it will be tested with other, unspecified types. But given that there are errors elsewhere in specification, it is quite likely that this was an oversight to use T[] instead of something like List<T>.

However it is good to know that I'm not simply misunderstanding something about generics.

Colonel J
Jan 3, 2008
I'm taking an intro programming class and we're using java. The program we're working on has to check the number of arguments that are fed into the command line when you start it, like "java Location 1 1 1". There has to be 3.

Anyway, I got it working by going with
code:

	if (args.length != 3)
    	{

    	    System.out.println("invalid");
	}
	else

    	{
          "the program"

    
It looks kinda weird, and I don't know if it's the appropriate way to do it. It works, however. It wouldn't work with

code:

	if (args.length = 3)
    	{

    	   "the program"

	}
	else

    	{
          System.out.println("invalid");

    
Anybody have an idea what's wrong with the second bit of code?

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
The = operator is not the same as the == operator. You need to use == in order to compare two numbers.

RichardA
Sep 1, 2006
.
Dinosaur Gum

Colonel J posted:

It looks kinda weird
Instead of placing the rest of the program in a else statement you can call the exit(int status) method in system.
code:
  if (args.length != 3){
    System.err.println("Invalid number of arguments: "+args.length);
    System.err.println("Expected 3");
    System.exit(1);
  }
  // Rest of program

Colonel J
Jan 3, 2008

RichardA posted:

Instead of placing the rest of the program in a else statement you can call the exit(int status) method in system.
code:
  if (args.length != 3){
    System.err.println("Invalid number of arguments: "+args.length);
    System.err.println("Expected 3");
    System.exit(1);
  }
  // Rest of program

This is awesome, thank you. Looks much better that way.

Meat Treat: Oops, I forgot to copy the "==". However, I used it and it still wouldn't work. It gave me an error in the terminal, I can't remember which however.

Jethro
Jun 1, 2000

I was raised on the dairy, Bitch!

Colonel J posted:

Anybody have an idea what's wrong with the second bit of code?
You almost certainly had a typo or copy/paste screw up somewhere in "the program".

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'm having a stupid problem writing strings over sockets in Java when I am using linux. What I'm trying to do works fine in Windows.

When I use PrintWriter to send a string command over a socket in Linux using println(message), it chops the last character off, so if the message was "/data" the other end only gets "/dat". I know linux only uses a line feed instead of a line feed and carriage return like windows as the separator, but the println command uses the separator for the platform, so that shouldn't matter.

I tried lots of different mixing up of line feeds, carriage returns, and null terminators, but it didn't work. I even converted the string to a char array, appended a null terminator, then a line feed, and used .print(charArray) and it still doesn't work. Every permutation doesn't work. I also noticed if I added another null terminator to the end of the string, it would chop off 2 characters instead of just one.

So far I've been able to jury rig it by checking the platform, and if its linux, to add an extra space so that space just gets chopped off instead of the end of my message, but I'm not satisfied.

Kaltag fucked around with this message at 12:56 on Sep 29, 2009

yatagan
Aug 31, 2009

by Ozma

Kaltag posted:

I'm having a stupid problem writing strings over sockets in Java when I am using linux. What I'm trying to do works fine in Windows.

When I use PrintWriter to send a string command over a socket in Linux using println(message), it chops the last character off, so if the message was "/data" the other end only gets "/dat". I know linux only uses a line feed instead of a line feed and carriage return like windows as the separator, but the println command uses the separator for the platform, so that shouldn't matter.

I tried lots of different mixing up of line feeds, carriage returns, and null terminators, but it didn't work. I even converted the string to a char array, appended a null terminator, then a line feed, and used .print(charArray) and it still doesn't work. Every permutation doesn't work. I also noticed if I added another null terminator to the end of the string, it would chop off 2 characters instead of just one.

You seem convinced that it's the sender's fault. What are you doing to receive the PrintWriter's output?

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?
The other side is an embedded system that runs a very unrobust FTP server. I only know that the last character is getting chopped because when I send "CWD /data" it returns with "Can't open directory /dat". My boss wrote the embedded FTP and perhaps he didn't anticipate the different line separators for linux and windows. I'm going to work on it some more before I walk up to him and tell him that his code is wrong.

tef
May 30, 2004

-> some l-system crap ->

Kaltag posted:

The other side is an embedded system that runs a very unrobust FTP server. I only know that the last character is getting chopped because when I send "CWD /data" it returns with "Can't open directory /dat". My boss wrote the embedded FTP and perhaps he didn't anticipate the different line separators for linux and windows. I'm going to work on it some more before I walk up to him and tell him that his code is wrong.

You need to send \r\n anyway

From: http://www.faqs.org/rfcs/rfc959.html

Edit: correct citing
code:
   The File Transfer Protocol follows the specifications of the Telnet
   protocol for all communications over the control connection.  Since
   the language used for Telnet communication may be a negotiated
   option, all references in the next two sections will be to the
   "Telnet language" and the corresponding "Telnet end-of-line code".
   Currently, one may take these to mean NVT-ASCII and <CRLF>.  No other
   specifications of the Telnet protocol will be cited.

   FTP commands are "Telnet strings" terminated by the "Telnet end of
   line code".
And it sounds like the dinky ftp server is dropping the last two characters assuming they are \r\n


Edit: His code *should* try to accomodate other line endings, as per postel's law, but your code should be sending the right thing in the first place.

Never use println on a wire protocol: always use the correct line endings for the protocol, not the platforms ones.

tef fucked around with this message at 14:34 on Sep 29, 2009

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?
excellent, thanks

yatagan
Aug 31, 2009

by Ozma
org.dom4j.InvalidXPathException: Invalid XPath expression: '//RECORD'. Caused by: org/jaxen/dom4j/Dom4jXPath

code:
//reader is org.dom4j.io.SAXReader, returns org.dom4j.Document which extends org.dom4j.Node

transactionDoc = reader.read(inputFile);
List transactionList = transactionDoc.selectNodes("//RECORD");
Any thoughts on why I'm seeing this error? I'm migrating some old code that has worked forever, and suddenly I have an invalid XPath.

Gingerbread Wife
Dec 28, 2003

~*~ iM At ThE mOtHeRfUcKiN sToP n Go ~*~
Quick question for a lab in my "Welcome to Java" class at school.

I'm creating a class that models natural numbers, BigNatural. One of the constructors in this class must take an object created from this class. Like so:

public BigNatural(BigNatural bn) {code...}

I am just using an int to model the natural number (with error checking when decrementing the int, etc in the various methods).

But anyway I have no idea how to get this BigNatural object that I'm passing to this constructor to spit out the int it's holding, in order to set the int in the new object. Not much luck searching online. Any pointers?

Edit: wow i'm retarded that was easy. this.bigNatural = bn.bigNatural;

Gingerbread Wife fucked around with this message at 03:47 on Oct 5, 2009

HFX
Nov 29, 2004

Gingerbread Wife posted:

Quick question for a lab in my "Welcome to Java" class at school.

I'm creating a class that models natural numbers, BigNatural. One of the constructors in this class must take an object created from this class. Like so:

public BigNatural(BigNatural bn) {code...}

I am just using an int to model the natural number (with error checking when decrementing the int, etc in the various methods).

But anyway I have no idea how to get this BigNatural object that I'm passing to this constructor to spit out the int it's holding, in order to set the int in the new object. Not much luck searching online. Any pointers?

Edit: wow i'm retarded that was easy. this.bigNatural = bn.bigNatural;

Always remember, a class can always touch the private data of another object of its class. You could also use a private get function also. It looks like you are doing a copy constructor which you can do through clone (and overriding as necessary if you need deep copy).

ComptimusPrime
Jan 23, 2006
Computer Transformer
Hey guys, I need some help with some code I am writing for my intro to programming class.

The problem involves analyzing the vertical position of a cannonball. We are supposed to take the input of the initial velocity (and for the purposes of this assignment I guess we are not paying attention to angles and for all intents and purposes the cannon is firing straight up, the physics don't really matter). We are supposed to find its position every 1/100th of a second, and print to the screen its position every one second. I have gotten everything down to where it will print out EVERYTHING but cannot get it to print just every one second. So here is the code I have currently.

code:
import java.util.*;

class CannonBall

{ public static void main(String[]args)
	{Scanner in = new Scanner(System.in);


double deltaT=0.01 , s=0 , so = 0 , T= 0, g = 9.8;

System.out.print("We're simulating a cannon ball flight today - Please enter the initial speed of the canon ball (in meters/sec) : ");

double v = in.nextDouble();

double Vo = v;

while(s>=0)

{

	s = s + v * deltaT ;

	v = v - g * deltaT ;

	T=T+deltaT;

	if(T%1==0)
	System.out.println("The cannonball is at " +s);
}
}
}
I introduced the variable T and set it equal to itself + deltaT (which equals 0.01). And I figured that whenever T was equal to a whole number (and thus a whole second) it would be divisible by 1 with no remainder. So the if statement (and I'm obviously wrong here) should make it print out the position "s" at every 1 second interval. However, every time I do this the program just ends with no printout. Can someone help me see what I'm doing wrong here?

PS
I hope I didn't break any rules for the forum or anything. I tried to get in to the right area and don't have enough time right now to read all of the full rules. Sorry in advance if I screwed up.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Much like decimal arithmetic isn't exact when dividing by numbers that aren't powers of 10 (or factors thereof), binary floating-point arithmetic is not exact when representing numbers that can't be represented as an integer multiplied by a power of 2. Thus adding .01 to 0 100 times is not guaranteed to produce exactly 1.

The easiest way to solve this is to count iterations using a separate, integer counter, and just print out every 100 iterations.

ComptimusPrime
Jan 23, 2006
Computer Transformer

rjmccall posted:

Much like decimal arithmetic isn't exact when dividing by numbers that aren't powers of 10 (or factors thereof), binary floating-point arithmetic is not exact when representing numbers that can't be represented as an integer multiplied by a power of 2. Thus adding .01 to 0 100 times is not guaranteed to produce exactly 1.

The easiest way to solve this is to count iterations using a separate, integer counter, and just print out every 100 iterations.

Thank you. That did the trick. And I'm sure that tidbit will help me a whole hell of a lot in the future.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

ComptimusPrime posted:

Thank you. That did the trick. And I'm sure that tidbit will help me a whole hell of a lot in the future.

Just so that you know, if you really do need that kind of precision in your calculations checkout the BigDecimal class.

ComptimusPrime
Jan 23, 2006
Computer Transformer

MEAT TREAT posted:

Just so that you know, if you really do need that kind of precision in your calculations checkout the BigDecimal class.

Thanks, I appreciate it. I don't quite need that much precision. It just said to use double precision fps so I went with it. I am not quite sure why you would want them in a problem like this where the actual level of accuracy doesn't extend beyond 0.1 with a nice estimated hundredth. Of course, they have not done anything in our book with single precision fps. I imagine it is just to keep it simple.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
The reason you won't see too many operations with floats is because of the constant casting you have to do since Java treats all literal floating point numbers as doubles.

If you mix a float with a double it will return a double because if will convert the float to a double to do the operation. But it won't convert the result back down to a float because of the possible loss of precision, so you have to do it manually with a cast.

Here's a quick example. If you just write 2.5 Java treats it as a double, you have to either cast it to a float or append an f to the end 2.5f. If you aren't careful you can do things like like this.

code:
float x = 2.5f;
float y = x / 5.0;
Luckily most of the time the compiler will throw an error or warn you, but it can be a huge wtf the first time you deal with it.

Here is some more reading if you are interested. http://mindprod.com/jgloss/floatingpoint.html

DholmbladRU
May 4, 2006
I am posting here because java is the language which is most fimiliar to me.

I have been asked by my campus job to think about how to extract data from an excel spreadsheet. I figure I can probably write a simple java program. All of the columns are static(or Ill tell them they have to be). And I only need to be able to search on a few fields. My question is, how can I go about outputting an excel file.

RussianManiac
Dec 27, 2005

by Ozmaugh

DholmbladRU posted:

I am posting here because java is the language which is most fimiliar to me.

I have been asked by my campus job to think about how to extract data from an excel spreadsheet. I figure I can probably write a simple java program. All of the columns are static(or Ill tell them they have to be). And I only need to be able to search on a few fields. My question is, how can I go about outputting an excel file.

http://jexcelapi.sourceforge.net/

First result after googling Java Excel.

RussianManiac fucked around with this message at 17:09 on Oct 7, 2009

Fly
Nov 3, 2002

moral compass

DholmbladRU posted:

I am posting here because java is the language which is most fimiliar to me.

I have been asked by my campus job to think about how to extract data from an excel spreadsheet. I figure I can probably write a simple java program. All of the columns are static(or Ill tell them they have to be). And I only need to be able to search on a few fields. My question is, how can I go about outputting an excel file.
You do not want to parse an Excel spreadsheet on your own. The file format for Excel 97 (common still) basically contains it's own mini-FAT file system, which was probably very useful when computers could not hold the entire file in RAM, but now makes handling the file rather difficult.

Jexcel is pretty good, but there is also the Apache POI project, which might be okay. POI used about 10x the memory that Jexcel did when I evaluated them years ago (2004), but the developers may have fixed some things since then.

edit: It may be a lot easier to deal with CSV files if you can control how the data is exported from Excel. Otherwise, Jexcel is pretty easy to use.

Fly fucked around with this message at 17:47 on Oct 7, 2009

zootm
Aug 8, 2006

We used to be better friends.

Fly posted:

Jexcel is pretty good, but there is also the Apache POI project, which might be okay. POI used about 10x the memory that Jexcel did when I evaluated them years ago (2004), but the developers may have fixed some things since then.
This was my impression about the same time as well, although POI development seems to have picked up since then so it might actually be the better option now. I remember meaning to look at it again but I've not had any reason to interoperate Java and Office since then.

Volguus
Mar 3, 2009

zootm posted:

This was my impression about the same time as well, although POI development seems to have picked up since then so it might actually be the better option now. I remember meaning to look at it again but I've not had any reason to interoperate Java and Office since then.

I have personally used Apache POI (http://poi.apache.org/) for both writing and reading excel files (last time I used them was 6 months ago) , and I was very pleased with the result.
Haven't used JExcel yet, but I will certainly give it a try next time I have to produce an excel report from a java application (being it web or desktop).

Fly
Nov 3, 2002

moral compass

rhag posted:

I have personally used Apache POI (http://poi.apache.org/) for both writing and reading excel files (last time I used them was 6 months ago) , and I was very pleased with the result.
Haven't used JExcel yet, but I will certainly give it a try next time I have to produce an excel report from a java application (being it web or desktop).
Have you tried using POI to write a 1 million cell spreadsheet? Did it work without generating an OOM (even with a 1GB heap) and taking forever? That was one of the failure modes we saw, and I would be happy to know whether it has been fixed.

JoeWindetc
Jan 14, 2007
JoeWindetc
::edit::

Got it.

JoeWindetc fucked around with this message at 05:46 on Oct 9, 2009

Parantumaton
Jan 29, 2009


The OnLy ThInG
i LoVe MoRe
ThAn ChUgGiNg SeMeN
iS gEtTiNg PaId To Be A
sOcIaL MeDiA sHiLl
FoR mIcRoSoFt
AnD nOkIa

Fly posted:

Have you tried using POI to write a 1 million cell spreadsheet? Did it work without generating an OOM (even with a 1GB heap) and taking forever? That was one of the failure modes we saw, and I would be happy to know whether it has been fixed.

POI is designed to be one of those API:s which build everything in memory and then dump the final result into wherever you direct it to dump so no, any POI API -inlucing HSSF - will most likely never allow you to use it for massive spreadsheets etc.

JoeWindetc
Jan 14, 2007
JoeWindetc
Pretty simple, but how can I compare column1 to column2?

column1 column2
------- -------
item1 [item1]
item2 [item2]
item3 [item3]
item4 [item4]
item5 [item5]

Both are in ArrayLists and I was under the impression I initialized them the same, but when I do a test print, I get the above. Any thoughts? Thanks.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
The objects in column2 are almost certainly lists or sets of some kind rather than individual objects. That they happen to only contain one object is irrelevant.

The easiest way to avoid this problem is to use generic typing properly, but I would guess you're not quite to that point of the learning curve yet. But bear it in mind.

JoeWindetc
Jan 14, 2007
JoeWindetc

rjmccall posted:

The objects in column2 are almost certainly lists or sets of some kind rather than individual objects. That they happen to only contain one object is irrelevant.

The easiest way to avoid this problem is to use generic typing properly, but I would guess you're not quite to that point of the learning curve yet. But bear it in mind.

Will do, thanks for the heads up, and yes, still learning.

yatagan
Aug 31, 2009

by Ozma
As for the "how" given your data, one of the below should work for you:

code:
if (array1.size() == array2.size()) {
	for (int i = 0; i < array1.size(); i++) {
		if (!array2.get(0).get(0).equals(array1.get(0))) {
			System.err.println("Not equal");
		}
	}
}
code:
if (array1.size() == array2.size()) {
	for (int i = 0; i < array1.size(); i++) {
		if (!array2.get(0)[0].equals(array1.get(0))) {
			System.err.println("Not equal");
		}
	}
}
For generic typing I think what rjmccall is getting at is something like this:

code:
private static void compareArrays(List<T> array1, List<T> array2) {
	if (array1.size() == array2.size()) {
		for (int i = 0; i < array1.size(); i++) {
			if (!array1.get(0).equals(array2.get(0)) {
				System.err.println("Not equal");
			}
		}
	}
}

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
All I mean by generic typing is that if you always use appropriate type parameters on your collections (e.g. ArrayList<String>), and you never work around the type system by letting their types decay (e.g. to a naked ArrayList), it will not be possible to ever accidentally put the wrong kinds of object in the collection (e.g. lists of strings instead of strings).

necrobobsledder
Mar 21, 2005
Lay down your soul to the gods rock 'n roll
Nap Ghost

zootm posted:

Of course you could consider scaling out instead of up with something like Terracotta, which to me looks like black magic.
We use that here for our clustering strategy (we were on jGroups+ Apache load balancing for a while *shudder*) and it's actually worked out quite well.

Adbot
ADBOT LOVES YOU

Parantumaton
Jan 29, 2009


The OnLy ThInG
i LoVe MoRe
ThAn ChUgGiNg SeMeN
iS gEtTiNg PaId To Be A
sOcIaL MeDiA sHiLl
FoR mIcRoSoFt
AnD nOkIa

necrobobsledder posted:

We use that here for our clustering strategy (we were on jGroups+ Apache load balancing for a while *shudder*) and it's actually worked out quite well.

Being interested in dynamic clustering, how does Terracotta scale in practice, do I have to bring the whole cluster down to add more nodes or can I dynamically pour more resources into it, what are the limits/caveats you've hit at with it etc?

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