What is the difference between Collection and List in Java?

First off: a List is a Collection. It is a specialized Collection, however.

A Collection is just that: a collection of items. You can add stuff, remove stuff, iterate over stuff and query how much stuff is in there.

A List adds the information about a defined sequence of stuff to it: You can get the element at position n, you can add an element at position n, you can remove the element at position n.

In a Collection you can’t do that: “the 5th element in this collection” isn’t defined, because there is no defined order.

There are other specialized Collections as well, for example a Set which adds the feature that it will never contain the same element twice.

http://stackoverflow.com/questions/3317381/what-is-the-difference-between-collection-and-list-in-java

java.util.Date vs java.sql.Date

Congratulations, you’ve hit my favorite pet peeve with JDBC: Date class handling.

Basically databases usually support at least three forms of datetime fields which are date, time and timestamp. Each of these have a corresponding class in JDBC and each of them extend java.util.Date. Quick semantics of each of these three are the following:

  • java.sql.Date corresponds to SQL DATE which means it stores years, months and days while hour, minute, second and millisecond are ignored. Additionally sql.Date isn’t tied to timezones.
  • java.sql.Time corresponds to SQL TIME and as should be obvious, only contains information abouthour, minutes, seconds and milliseconds.
  • java.sql.Timestamp corresponds to SQL TIMESTAMP which is exact date to the nanosecond (note that util.Date only supports milliseconds!) with customizable precision.

One of the commonest bugs in JDBC drivers in relation to these three types is that the types are handled incorrectly. This means that sql.Date is timezone specific, sql.Time contains current year, month and day et cetera et cetera.

Finally: Which one to use?

Depends on the SQL type of the field, really. PreparedStatement has setters for all three values, #setDate() being the one for sql.Date, #setTime() for sql.Time and #setTimestamp() for sql.Timestamp.

Do note that if you use ps.setObject(fieldIndex, utilDateObject); you can actually give a normal util.Date to most JDBC drivers which will happily devour it as if it was of the correct type but when you request the data afterwards, you may notice that you’re actually missing stuff.

I’m really saying that none of the Dates should be used at all.

What I am saying that save the milliseconds/nanoseconds as plain longs and convert them to whatever objects you are using (obligatory joda-time plug). One hacky way which can be done is to store the date component as one long and time component as another, for example right now would be 20100221 and 154536123. These magic numbers can be used in SQL queries and will be portable from database to another and will let you avoid this part of JDBC/Java Date API:s entirely.

http://stackoverflow.com/questions/2305973/java-util-date-vs-java-sql-date

Choosing between java.util.Date or java.sql.Date

The question and other answers seem to be over-thinking the issue.

A java.sql.Date is merely a java.util.Date with its time set to 00:00:00.

Date-Only versus Date-Time

The core problem is:

  • SQL
    In SQL, the DATE data type stores a date-only, without a time-of-day.
  • JAVA
    In the badly designed date-time library bundled with the early versions of Java, they failed to include a class to represent a date-only.

Instead of creating a date-only class, the Java team made a terrible hack. They took their date-time class (the misnamed java.util.Date class, containing both date and time) and extended it to have an instance set its time-of-day to midnight UTC, 00:00:00. That hack, that subclass of j.u.Date, is java.sql.Date.

All this hacking, poor design, and misnaming has made a confusing mess.

Which To Use

So when to use which? Simple, after cutting through the confusion.

  • When reading or writing to a database’s date-only column, use java.sql.Date as it clumsily tries to mask its time-of-day.
  • Everywhere else in Java, where you need a time-of-day along with your date, use java.util.Date.
  • When you have a java.sql.Date in hand but need a java.util.Date, simply pass the java.sql.Date. As a subclass, a java.sql.Date is a java.util.Date.

Even Better

In modern Java, you know have a choice of decent date-time libraries to supplant the old and notoriously troublesome java.util.Date, .Calendar, SimpleTextFormat, and java.sql.Date classes bundled with Java. The main choices are:

Both offer a LocalDate class to represent a date only, with no time-of-day and no time zone.

Modernized JDBC

Hopefully JDBC will be updated to provide getter and setter methods for the java.time LocalDate.

setObject | getObject

This article published by Oracle suggests that indeed the JDBC in Java 8 has been updated transparently to map a SQL DATE value to the new java.time.LocalDate type if you call getObject and setObjectmethods.

In obtuse language, the bottom of the JDBC 4.2 update spec confirms that article, with new mappings added to the getObject and setObject methods.

Convert

The spec also says new methods have been added to the java.sql.Date class to convert back and forth to java.time.LocalDate.

http://stackoverflow.com/questions/24650186/choosing-between-java-util-date-or-java-sql-date

Use of final class in Java

If they do, when do they use it so I can understand it better and know when to use it.

A final class is simply a class that can’t be extended.

(This does not mean that all references to objects of the class would act as if they were declared as final.)

When it’s useful to declare a class as final is covered in the answers of this question:

If Java is object oriented, and you declare a class FINAL, doesn’t it stop the idea of class having the characteristics of objects?

In some sense yes.

By marking a class as final you disable a powerful and flexible feature of the language for that part of the code. Some classes however, should not (and in certain cases can not) be designed to take subclassing into account in a good way. In these cases it makes sense to mark the class as final, even though it limits OOP. (Remember however that a final class can still extend another non-final class.)

http://stackoverflow.com/questions/5181578/use-of-final-class-in-java

Oracle: How to find out if there is a transaction pending?

you can check if your session has a row in V$TRANSACTION (obviously that requires read privilege on this view):

SQL> SELECT COUNT(*)
  2    FROM v$transaction t, v$session s, v$mystat m
  3   WHERE t.ses_addr = s.saddr
  4     AND s.sid = m.sid
  5     AND ROWNUM = 1;

  COUNT(*)
----------
         0

SQL> insert into a values (1);

1 row inserted

SQL> SELECT COUNT(*)
  2    FROM v$transaction t, v$session s, v$mystat m
  3   WHERE t.ses_addr = s.saddr
  4     AND s.sid = m.sid
  5     AND ROWNUM = 1;

  COUNT(*)
----------
         1

SQL> commit;

Commit complete

SQL> SELECT COUNT(*)
  2    FROM v$transaction t, v$session s, v$mystat m
  3   WHERE t.ses_addr = s.saddr
  4     AND s.sid = m.sid
  5     AND ROWNUM = 1;

  COUNT(*)
----------
         0

http://stackoverflow.com/questions/1299694/oracle-how-to-find-out-if-there-is-a-transaction-pending

sorting class array java

[…] How should Java Comparator class be declared to sort the arrays by their first elements in decreasing order […]

Here’s a complete example using Java 8:

import java.util.*;

public class Test {

    public static void main(String args[]) {

        int[][] twoDim = { {1, 2}, {3, 7}, {8, 9}, {4, 2}, {5, 3} };

        Arrays.sort(twoDim, Comparator.comparing((int[] arr) -> arr[0])
                                      .reversed());

        System.out.println(Arrays.deepToString(twoDim));
    }
}

Output:

[[8, 9], [5, 3], [4, 2], [3, 7], [1, 2]]

For Java 7 you can do:

Arrays.sort(twoDim, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return Integer.compare(o2[0], o1[0]);
    }
});

If you unfortunate enough to work on Java 6 or older, you’d do:

Arrays.sort(twoDim, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return ((Integer) o2[0]).compareTo(o1[0]);
    }
});

http://stackoverflow.com/questions/5393254/java-comparator-class-to-sort-arrays

Validating XML against XSD

Returns simply true or false (also you don’t need any external library):

static boolean validateAgainstXSD(InputStream xml, InputStream xsd)
{
    try
    {
        SchemaFactory factory = 
            SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(xsd));
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(xml));
        return true;
    }
    catch(Exception ex)
    {
        return false;
    }
}

http://stackoverflow.com/questions/6815579/validating-xml-against-xsd

Getting current Year and Month resulting strange results

Just to give a bit more background:

Both new GregorianCalendar() and Calendar.getInstance() will correctly give a calendar initialized at the current date and time.

MONTH and YEAR are constants within the Calendar class. You should not use them “via” a reference which makes it look like they’re part of the state of an object. It’s an unfortunate part of the design of the Calendar class that to access the values of different fields, you need to call get with a field number, specified as one of those constants, as shown in other answers:

Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);

Note that the month numbers are 0-based, so at the time of this writing (in April) the month number will be 3.

It’s an unfortunate part of the design of the Java language that you can reference static members (such as constants) via expressions of that type, rather than only through the type name.

My recommendations:

  • If your IDE allows it (as Eclipse does), make expressions such as c.YEAR give a compile-time error – you’ll end up with much clearer code if you always use Calendar.YEAR.
  • Where possible, use Joda Time – a much better date/time library for Java. Admittedly on Android you may be a bit space-constrained, but if your app does a lot of date/time manipulation, it would save you a lot of headaches.

http://stackoverflow.com/questions/10161637/getting-current-year-and-month-resulting-strange-results

“Non-resolvable parent POM: Could not transfer artifact” when trying to refer to a parent pom from a child pom with ${parent.groupid}

Looks like you’re trying to both inherit the groupId from the parent, and simultaneously specify the parent using an inherited groupId!
In the child pom, use something like this:
4.0.0


org.felipe
tutorial_maven
1.0-SNAPSHOT
../pom.xml


tutorial_maven_jar
Using properties like ${project.groupId} won’t work there. If you specify the parent in this way, then you can inherit the groupId and version in the child pom. Hence, you only need to specify the artifactId in the child pom.