开发者

Array of Dates in Java

开发者 https://www.devze.com 2022-12-13 01:21 出处:网络
I know how to create an array of strings or integers, but how does one create a开发者_Python百科n array of dates :/ The same way you do for Stringand Int , you just place different types inside:

I know how to create an array of strings or integers, but how does one create a开发者_Python百科n array of dates :/


The same way you do for String and Int , you just place different types inside:

Date [] dates = {
    new Date(), 
    new Date()
 };

Declared an array of size two with two dates.

You can also initialize with null values:

 Date [] dates = new Date[2];

Or add more significant values:

 Date [] dates = {
    getDateFromString("25/11/2009"), 
    getDateFromString("24/12/2009")
 };

.... 
public Date getDateFromString( String s ) {
    Date result = ...// parse the string set the value etc. 
    return result;
}

EDIT

...but is there anyway you can finish up what you were doing in the getDateFromString method?

Sure, I didn't initially because my point was to show, that you could put anything that is of type "Date" there.

You just have to use the SimpleDateFormate.parse() method ( inherited from DateFormat class )

  simpleDateFormatInstance.parse( "24/12/2009" ); // returns christmas 2009.

Here's a complete working sample:

import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
import static java.lang.System.out;

public class DateArrayTest {

    private static final SimpleDateFormat dateFormat 
                   = new SimpleDateFormat("dd/MM/yyyy");
    private static final Date invalidDate = new Date(0);


    // test creating a date from a string.
    public static void main( String [] args ) { 
        Date [] randomDates = {
            fromString("01/01/2010"), // new year
            fromString("16/09/2010"), // 200 yrs Mex indepence 
            fromString("21/03/2010"), // uhhmm next spring?
            fromString("this/should/fail"), // invalid date.
        };

        for( Date date: randomDates ) {
            print( date );
        }
    }

    /**
     * Creates a date from the given string spec. 
     * The date format must be dd/MM/yyyy ie. 
     * 24 december 2009 would be: 24/12/2009
     * @return invalidDate if the format is invalid.
     */
    private static final Date fromString( String spec ) {
        try {
            return dateFormat.parse( spec );
        } catch( ParseException dfe ) {
            return invalidDate;
        }
    }
    private static final void print( Date date ) {
        if( date == invalidDate ) {
            out.println("Invalid date");
        } else {
            out.println( dateFormat.format( date ) );
        }
    }
}


you can use an array of java.util.Date (API docs are here)

Date[] dates = new Date[] {
    new Date(),
    new Date(),
};

You can create an array of any object type in java - all reference and primitive types


Or you could use the Collections API and Calendar class,

import java.util.*;

List<Calendar> dates = new ArrayList<Calendar>(5); // initial size
dates.add( Calendar.getInstance() );


Did you mean inputting an array of dates.This code would help..

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;

public class Datinput {

    public static void main(String args[]) {
        int n;
        ArrayList<String> al = new ArrayList<String>();
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        String da[] = new String[n];
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        sdf.setLenient(false);
        Date date[] = new Date[n];
        in.nextLine();
        for (int i = 0; i < da.length; i++) {
            da[i] = in.nextLine();
        }
        for (int i = 0; i < da.length; i++) {

            try {
                date[i] = sdf.parse(da[i]);
            } catch (ParseException e) {

                e.printStackTrace();
            }
        }

        in.close();
    }
}


You can consider (and this is not reality, but it sort of works this way) that primitives are something like this (I do get to reality later on... so keep reading):

int.7, int.42 (won't compile) where int is a class (it is not) and 7 and 42 are public static final variables (they are not).

and that Strings are something like this:

String."Hello", String."world" (won't compile) where String is a class (it is) and "Hello" and "world" are public static final variables (they are not).

If my fake reality were true you would have to have something like:

// again, won't compile.
public class int
{
    public static final int 7 = new int(7);
    public static final int 42 = new int(42);
    private final ??? data;

    public int(??? val)
    {
        data = val;
    }
}

and

// also will not compile
public class String
{
    public final String "Hello" = new String("Hello);
    public final String "world" = new String("world);
    private final ??? data;

    public String(final ??? val)
    {
        data = val;
    }
}

now you make a an array like (still won't compile):

int[] array = new int[] { int.7, int.42 };
String[] array = new String[] {String."Hello", String."world" };

In the case of String my alternate reality would be very silly since it is impossible for the String class to know in advance every single possible String (for int it is possible).

So we would get rid of the public static final variables in String and do this instead:

String[] array = new String[] { new String("Hello"), new String("world") };

Now to reality:

When the java compiler, when it sees "Hello" or "world" it does something similar to "new String("Hello")" - it is a bit smarter so that if you have "Hello" 20 times in a file that there is only one copy (and some other things too).

When you say:

new int[100]; you get an array of 100 ints all set to 0.
new String[100]; you get an array of 100 Strings all pointing to null.
new Data[100]; you get 100 Dates all pointing to null.

Since the String and the Date ones are pointing to null you need to allocate a new object for each one. The reason that you don't have to say "new" with String is that the compiler treats is specially. The reason you do not have to say "new" with int is that it is a primitive instead of an object.

So, the easy answer to your question is, you have to allocate a new Date for each element of the array :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消